{"text": "function out = isdecay(f)\n%ISDECAY Test if a SINGFUN decays faster than a single root at endpoints.\n% ISDECAY(F) returns a 1x2 row vector each of which indicates whether F\n% vanishes at one of the endpoints faster than a single root. An entry TRUE is\n% returned if F has a boundary root with multiplicity larger than one, FALSE\n% otherwise. \n%\n% Note that ISDECAY is designed for and expected to be called only by UNBNDFUN\n% class for handling functions defined on unbounded domains.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nout = isdecay(f.smoothPart);\n\n%% Left endpoint:\n\nif ( ~out(1) && f.exponents(1) > 1 )\n out(1) = 1;\nend\n\n%% Right endpoint:\n\nif ( ~out(2) && f.exponents(2) > 1 )\n out(2) = 1;\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/@singfun/isdecay.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.39999754232136026}}
{"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": "function M = ply_read(filename)\n% Read PLY-formatted data from disk\n% FORMAT M = ply_read(filename)\n%\n% filename - PLY-formatted file name\n% M - data structure\n%__________________________________________________________________________\n% \n% Stanford Triangle Format Specification:\n% https://en.wikipedia.org/wiki/PLY_%28file_format%29\n%__________________________________________________________________________\n% Copyright (C) 2017-2019 Wellcome Trust Centre for Neuroimaging\n\n% Guillaume Flandin\n% $Id: ply_read.m 7676 2019-10-22 10:19:29Z guillaume $\n\n\nfid = fopen(filename,'rt');\nif fid == -1\n error('Cannot open %s.',filename);\nend\n\nM = struct('vertices',[],'faces',[]);\n\n%-Read header\nisvertex = false;\nnval = 0;\nwhile true\n l = fgetl(fid);\n if strcmp(l,'end_header'), break; end\n [l,r] = strtok(l);\n if strcmp(l,'element')\n [l,r] = strtok(r);\n switch l\n case 'vertex'\n nv = str2double(r);\n isvertex = true;\n case 'face'\n nf = str2double(r);\n isvertex = false;\n end\n elseif strcmp(l,'property')\n if isvertex\n nval = nval + 1;\n end\n end\nend\n\n%-Read data\nM.vertices = fscanf(fid,'%f',[nval nv])';\nM.vertices = M.vertices(:,1:3);\nM.faces = fscanf(fid,'%d',[4 nf])';\nM.faces = M.faces(:,2:4) + 1;\n\nfclose(fid);\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/@gifti/private/ply_read.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.3999975349934193}}
{"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": "classdef LevelSetWithCircleInclusion < LevelSetSphereNdim\n \n methods (Access = public)\n \n function obj = LevelSetWithCircleInclusion(cParams)\n obj.fracRadius = cParams.fracRadius;\n obj.compute(cParams);\n end\n end\n \n methods (Access = protected)\n function computeLevelSetValue(obj)\n ls = 1 - obj.dist;\n obj.levelSet = ls;\n end\n end\n \n \nend\n\n", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/Topology Optimization/DesignVaribleInitializer/LevelSetInitializer/LevelSetWithCircleInclusion.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.39996096144165316}}
{"text": "function tests = test_ft_preproc_detrend\n\n% MEM 1gb\n% WALLTIME 00:10:00\n% DEPENDENCY ft_preproc_detrend\n\nif nargout\n % assume that this is called by RUNTESTS\n tests = functiontests(localfunctions);\nelse\n % assume that this is called from the command line\n fn = localfunctions;\n for i=1:numel(fn)\n feval(fn{i});\n end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction testOptions(testCase)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nnchan = 8;\nnsample = 1000;\ndat = randn(nchan, nsample) + 1;\n\nresult = [];\nresult{end+1} = ft_preproc_detrend(dat, 1, 1000);\nresult{end+1} = ft_preproc_detrend(dat, 1, 900);\nresult{end+1} = ft_preproc_detrend(dat, 101, 1000);\nresult{end+1} = ft_preproc_detrend(dat, 101, 900);\n\n% all iterations were done with (slightly) different options, hence the results should not be equal\nfor i=1:numel(result)\n for j=(i+1):numel(result)\n assert(~isequal(result{i}, result{j}), 'the results %d and %d should not be equal', i, j);\n end\nend", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/test/test_ft_preproc_detrend.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.39996096144165316}}
{"text": "classdef GradientSurfPerimeterComputer < handle\n\n properties (Access = private)\n outPutFolder\n iMesh\n figureID\n gExperiment\n end\n\n properties (Access = private)\n inputFiles\n outputFolder\n levelSetParams\n circleCase\n end\n\n methods (Access = public)\n\n function obj = GradientSurfPerimeterComputer(cParams)\n obj.init(cParams)\n end\n\n function compute(obj)\n for im = 1:numel(obj.inputFiles)\n obj.iMesh = im;\n obj.createGradientVariationExperiment();\n nEpsilon = length(obj.gExperiment.regularizedPerimeter.epsilons);\n for iEpsilon = 1:nEpsilon\n obj.plotSurf(iEpsilon);\n obj.addXYlabel();\n obj.addTitle(iEpsilon);\n obj.printSurf(iEpsilon);\n end\n end\n end\n\n end\n\n methods (Access = private)\n\n function init(obj,cParams)\n obj.inputFiles = cParams.inputFiles;\n obj.outputFolder = cParams.outputFolder;\n obj.levelSetParams = cParams.levelSetParams;\n obj.circleCase = cParams.circleCase;\n end\n\n function createGradientVariationExperiment(obj)\n s.levelSetParams = obj.levelSetParams;\n s.inputFile = obj.inputFiles{obj.iMesh};\n s.iMesh = obj.iMesh;\n g = GradientVariationExperiment(s);\n obj.gExperiment = g;\n end\n\n function addXYlabel(obj)\n xlabel('$x$','interpreter','latex')\n ylabel('$y$','interpreter','latex')\n end\n\n function plotSurf(obj,iEpsilon)\n coord = obj.gExperiment.backgroundMesh.coord;\n x = coord(:,1);\n y = coord(:,2);\n dPer = obj.gExperiment.regularizedPerimeter.perimetersGradient;\n z = dPer(:,iEpsilon);\n tri = delaunay(x,y);\n f = figure();\n h = trisurf(tri,x,y,z);\n shading interp\n obj.figureID = f;\n ar = get(gca,'DataAspectRatio');\n obj.plotBoundaryCutMesh(tri,x,y,z)\n set(gca,'DataAspectRatio',ar);\n view(-60,25);\n end\n\n function plotBoundaryCutMesh(obj,tri,x,y,z)\n m = obj.computeBoundaryCutMesh();\n %nodes = unique(m.connec(:));\n Xi = m.coord(:,1);\n Yi = m.coord(:,2);\n Zi = interptri(tri,x,y,z,Xi,Yi);\n s.coord = [Xi Yi Zi];\n %s.connec(:,1) = 1:length(Xi);\n %s.connec(:,2) = 2:length(Xi)+1;\n %s.connec(end,2) = 1;\n %s.coord = m.coord;\n s.connec = m.connec;\n s.kFace = -2;\n mB = Mesh(s);\n hold on\n mB.plot\n % axes(axes_h)\n % axis(axis_h)\n % view(a,b)\n end\n\n function mBCut = computeBoundaryCutMesh(obj)\n g = obj.gExperiment;\n s.backgroundMesh = g.backgroundMesh;\n s.boundaryMesh = g.boundaryMesh;\n uMesh = UnfittedMesh(s);\n uMesh.compute(g.levelSet);\n bCut = uMesh.boundaryCutMesh;\n mBCut = bCut.mesh;\n end\n\n function printSurf(obj,iEpsilon)\n part1 = [obj.outputFolder,obj.circleCase,'GradientMesh',num2str(obj.iMesh)];\n part2 = ['Epsilon',num2str(iEpsilon)];\n outFile = [part1,part2];\n printer = surfPrinter(obj.figureID);\n printer.print(outFile)\n end\n\n function addTitle(obj,iEpsilon)\n epsilons = obj.gExperiment.regularizedPerimeter.epsilons;\n h = obj.gExperiment.backgroundMesh.computeMeanCellSize;\n epsStr = num2str(epsilons(iEpsilon)/h);\n firstStr = 'dPer^R_\\varepsilon \\ \\textrm{with} \\ \\,';\n secondStr = '\\varepsilon/h \\, = \\, ';\n thirdStr = '\\ \\textrm{and} \\ h/L \\, = \\, ';\n L = obj.gExperiment.domainLength;\n [n,d] = rat(h/L);\n if n == 1\n hStr = [num2str(n),'/',num2str(d)];\n else\n hStr = num2str(round(h/L,3));\n end\n titleStr = ['$',firstStr,secondStr,epsStr,thirdStr,hStr,'$'];\n title(titleStr,'interpreter','latex');\n end\n\n end\n\nend", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/Topology Optimization/Applications/PerimeterExperiments/GradientSurfPerimeterComputer.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.39996096144165316}}
{"text": "classdef AllEdges2CutEdgesComputer < handle\n \n properties (GetAccess = public, SetAccess = private)\n nCutEdgeByElem\n end\n \n properties (Access = private)\n isEdgeCutInElem\n end\n \n methods (Access = public)\n \n function obj = AllEdges2CutEdgesComputer(cParams)\n obj.init(cParams)\n end\n \n function edge = compute(obj,allEdges)\n nElem = size(allEdges,1);\n allEdges = transpose(allEdges);\n cutEdges = allEdges(obj.isEdgeCutInElem);\n cutEdges = reshape(cutEdges,obj.nCutEdgeByElem,nElem);\n edge = transpose(cutEdges);\n end\n \n \n end\n \n \n methods (Access = private)\n \n function init(obj,cParams)\n obj.isEdgeCutInElem = cParams.isEdgeCutInElem;\n obj.nCutEdgeByElem = unique(sum(obj.isEdgeCutInElem,1));\n end\n \n end\n \n \nend", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/FEM/Mesh/Unfitted/AllEdges2CutEdgesComputer.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.399960953793424}}
{"text": "function z = ge(x,y)\n%GE Greater than or equal for sptensors.\n%\n% See also SPTENSOR.\n%\n%MATLAB Tensor Toolbox.\n%Copyright 2015, Sandia Corporation.\n\n% This is the MATLAB Tensor Toolbox by T. Kolda, B. Bader, and others.\n% http://www.sandia.gov/~tgkolda/TensorToolbox.\n% Copyright (2015) Sandia Corporation. Under the terms of Contract\n% DE-AC04-94AL85000, there is a non-exclusive license for use of this\n% work by or on behalf of the U.S. Government. Export of this data may\n% require a license from the United States Government.\n% The full license terms can be found in the file LICENSE.txt\n\n\n%% Observations for sparse matrix case.\n% The result of a >= 5 is sparse.\n% The result of a >= 0 is sparse.\n% The result of a >= full(a) is sparse.\n\n%% Case 1: One argument is a scalar\nif isscalar(y)\n subs1 = x.subs((x.vals >= y),:);\n if y <= 0\n subs2 = setdiff(allsubs(x),x.subs,'rows');\n else\n subs2 = [];\n end\n z = sptensor([subs1;subs2],true,size(x));\n return;\nend\n\n% Call back with the arguments reversed.\nif isscalar(x)\n z = le(y,x);\n return;\nend\n\n%% Case 2: Both x and y are tensors of some sort\n% Check that the sizes match\nif ~isequal(x.size,y.size)\n error('Size mismatch');\nend\n\n% Case 2a: Two sparse tensors\nif isa(x,'sptensor') && isa(y,'sptensor')\n z = le(y,x);\n return;\nend\n\n% Case 2b: One dense tensor\nif isa(y,'tensor')\n\n % x zero \n subs1 = find(y <= 0);\n subs1 = setdiff(subs1,x.subs,'rows');\n \n % x nonzero\n subs2 = x.subs(x.vals >= y(x.subs,'extract'),:);\n \n % assemble\n z = sptensor([subs1;subs2],true,size(x));\n \n return;\n \nend\n\n%% Otherwise\nerror('The arguments must be two sptensors or an sptensor and a scalar.');\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u5206\u7c7b\u7b97\u6cd5/DEEP-TENSOR-FACTORIZATION-FOR-HYPERSPECTRAL-IMAGE-CLASSIFICATION-master/code/tensor_toolbox_2.6/@sptensor/ge.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.399960953793424}}
{"text": "function w = drfiLearnSaliencyFusionWeight( train_dir, gt_dir, num_segmentation, is_resize )\n % Assume that all training images are placed under train_dir.\n % The saliency maps of i-th segmentation are under the folder \"i\" (e.g., \n % saliency maps of 3rd segmentation are under the folder \"3\").\n % Detailed introduction on learning the saliency fusion weight can be\n % found in our supplementary material.\n \n M = num_segmentation;\n \n % Resize all training images to a fixed size 200*200\n sub_dir_list = dir(fullfile(train_dir, '*'));\n \n ind = [];\n for m = 1 : length(sub_dir_list)\n if strcmp(sub_dir_list(m).name, '.') || strcmp(sub_dir_list(m).name, '..')\n ind = [ind, m];\n continue;\n end\n end\n \n % Remove '.' and '..'\n sub_dir_list(ind) = [];\n \n normh = 200;\n normw = 200;\n \n % Resize\n if is_resize\n for m = 1 : length(sub_dir_list)\n image_list = dir(fullfile(train_dir, sub_dir_list(m).name, '*.png'));\n sub_dir_name = sub_dir_list(m).name;\n\n parfor n = 1 : length(image_list)\n image = imread(fullfile(train_dir, sub_dir_name, image_list(n).name));\n\n image = imresize(image, [normh, normw]);\n\n imwrite(image, fullfile(train_dir, sub_dir_name, image_list(n).name));\n\n% if mod(jx, 500) == 0\n% fprintf( 'sub_dir: %s, jx: %d\\n', sub_dir_name, jx );\n% end\n end\n \n fprintf( '%d / %d\\n', m, length(sub_dir_list) );\n end\n end\n \n image_list = dir(fullfile(train_dir, sub_dir_list(end).name, '*.png'));\n num_image = length(image_list);\n \n % prepare H and f\n H = zeros(M, M);\n f = zeros(M, 1);\n \n for ii = 1 : M * M\n [m, n] = ind2sub([M, M], ii);\n sub_dir_name_n = sub_dir_list(n).name;\n sub_dir_name_m = sub_dir_list(m).name;\n if m >= n\n temp = zeros(1, num_image);\n parfor k = 1 : num_image\n image_name = image_list(k).name;\n Akm = im2double(imread(fullfile(train_dir, sub_dir_name_m, image_name)));\n Akn = im2double(imread(fullfile(train_dir, sub_dir_name_n, image_name)));\n \n if size(Akm, 3) > 1\n Akm = rgb2gray( Akm );\n end\n \n if size(Akn, 3) > 1\n Akn = rgb2gray( Akn );\n end\n \n Nk = 1;%size(Akm, 1) * size(Akm, 2);\n temp(k) = sum(sum(Akm .* Akn)) / Nk;\n % fprintf( 'ix: %d, jx: %d, n: %d\\n', ix, jx, n );\n end \n H(m, n) = 2 * sum( temp );\n else\n H(m, n) = H(n, m);\n end\n \n fprintf( 'Computing H, m: %d, n: %d\\n', m, n );\n end\n H = H / num_image;\n save( 'H.mat', 'H' );\n% load( 'H.mat' );\n\n for m = 1 : M \n temp = zeros(1, num_image);\n sub_dir_name = sub_dir_list(m).name;\n parfor k = 1 : num_image\n image_name = image_list(k).name;\n Akm = im2double(imread(fullfile(train_dir, sub_dir_name, image_name)));\n if size(Akm, 3) > 1\n Akm = rgb2gray(Akm);\n end\n \n A = imread(fullfile(gt_dir, image_name));\n A = imresize(A, [normh, normw]);\n A = im2double( A );\n if size(A, 3) > 1\n A = rgb2gray(A);\n end\n \n A( A > 0.5 ) = 1.0;\n A( A < 0.5 ) = 0; \n \n % f(ix) = f(ix) - 2 * sum(sum(A .* Ani));\n % temp = temp - 2 * sum(sum(A .* Ani));\n Nk = 1;%size(A, 1) * size(A, 2);\n temp(k) = - 2 * sum(sum(A .* Akm)) / Nk;\n end \n f(m) = sum( temp );\n fprintf( 'comupting f, m: %d\\n', m );\n end \n f = f / num_image;\n save( 'f.mat', 'f' ); \n \n % Solve the quadratic programming problem\n w_init = ones(M, 1) / M;\n \n Aeq = ones(1, M);\n beq = 1;\n \n lb = zeros(M, 1);\n ub = ones(M, 1);\n \n opt = optimset( 'Algorithm', 'interior-point-convex' );\n w = quadprog(H, f, [], [], Aeq, beq, lb, ub, w_init, opt );\n \n w( w < 1e-6 ) = 0;\nend", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u68c0\u6d4b\u7b97\u6cd5/drfi_matlab-master/train/drfiLearnSaliencyFusionWeight.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.399960953793424}}
{"text": "%% Copyright (C) 2014-2022 Colin B. Macdonald\n%%\n%% This file is part of OctSymPy.\n%%\n%% OctSymPy is free software; you can redistribute it and/or modify\n%% it under the terms of the GNU General Public License as published\n%% by the Free Software Foundation; either version 3 of the License,\n%% or (at your option) any later version.\n%%\n%% This software is distributed in the hope that it will be useful,\n%% but WITHOUT ANY WARRANTY; without even the implied warranty\n%% of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See\n%% the GNU General Public License for more details.\n%%\n%% You should have received a copy of the GNU General Public\n%% License along with this software; see the file COPYING.\n%% If not, see .\n\n%% -*- texinfo -*-\n%% @documentencoding UTF-8\n%% @defmethod @@sym acos (@var{x})\n%% Symbolic acos function.\n%%\n%% Example:\n%% @example\n%% @group\n%% syms x\n%% y = acos (x)\n%% @result{} y = (sym) acos(x)\n%% @end group\n%% @end example\n%%\n%% Note: this file is autogenerated: if you want to edit it, you might\n%% want to make changes to 'generate_functions.py' instead.\n%%\n%% @end defmethod\n\n\nfunction y = acos(x)\n if (nargin ~= 1)\n print_usage ();\n end\n y = elementwise_op ('acos', x);\nend\n\n\n%!error acos (sym(1), 2)\n%!assert (isequaln (acos (sym(nan)), sym(nan)))\n\n%!shared x, d\n%! d = 1;\n%! x = sym('1');\n\n%!test\n%! f1 = acos(x);\n%! f2 = acos(d);\n%! assert( abs(double(f1) - f2) < 1e-15 )\n\n%!test\n%! D = [d d; d d];\n%! A = [x x; x x];\n%! f1 = acos(A);\n%! f2 = acos(D);\n%! assert( all(all( abs(double(f1) - f2) < 1e-15 )))\n\n%!test\n%! % round trip\n%! y = sym('y');\n%! A = acos (d);\n%! f = acos (y);\n%! h = function_handle (f);\n%! B = h (d);\n%! assert (A, B, -eps)\n", "meta": {"author": "cbm755", "repo": "octsympy", "sha": "c1ecd1e08f027d5101d0f4250dfc496aa98c8bcd", "save_path": "github-repos/MATLAB/cbm755-octsympy", "path": "github-repos/MATLAB/cbm755-octsympy/octsympy-c1ecd1e08f027d5101d0f4250dfc496aa98c8bcd/inst/@sym/acos.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.39975629619724684}}
{"text": "function ret=writesdpa(fname,A,b,c,K,pars)\n%WRITESDPA Take a problem in SeDuMi format and writes it in SDPA format \n%\n% Usage:\n%\n% ret=writesdpa(fname,A,b,c,K,pars)\n%\n% fname Name of SDPpack file, in quotes\n% A,b,c,K Problem in SeDuMi form\n% pars Optional parameters.\n% pars.printlevel=0 No printed output \n% pars.printlevel=1 (default) Some printed output.\n% \n% ret ret=0 on success, ret=1 on failure.\n%\n% Notes:\n%\n% Problems with complex data are not allowed. \n%\n% Quadratic cone and rotated cone constraints are not supported. \n%\n% Nonsymmetric A.s and C.s matrices are symmetrized with A=(A+A')/2\n% a warning is given when this happens.\n%\n% Free variables are not supported.\n%\n% Floating point numbers are written out with 18 decimal digits for\n% accuracy.\n%\n% Please contact the author (Brian Borchers, borchers@nmt.edu) with any\n% questions or bug reports.\n%\n% Third Version: 3/3/06. Corrected a bug in the handling of\n% nonsymmetric constraint matrices.\n%\n% Second Version: 7/14/04. Modified to vastly speed up operations on sparse\n% matrices. On some problems, this version is 100 times \n% faster! \n%\n% First Version: 7/14/03. Modified from old writesdp.m which wrote problems\n% in SDPPack format.\n%\n%\n%\n\n% This file is part of the Matlab Toolbox for Dimensionality Reduction.\n% The toolbox can be obtained from http://homepage.tudelft.nl/19j49\n% You are free to use, change, or redistribute this code in any way you\n% want for non-commercial purposes. However, it is appreciated if you \n% maintain the name of the original author.\n%\n% (C) Laurens van der Maaten, Delft University of Technology\n\n\n%\n% First, check to see whether or not we should be quiet.\n%\nif (nargin > 5)\n if (isfield(pars,'printlevel'))\n if (pars.printlevel == 0)\n quiet=1;\n else\n quiet=0;\n end\n else\n quiet=0;\n end\nelse\n pars.printlevel=1;\n quiet=0;\nend\n%\n% First, check for complex numbers in A, b, or c.\n%\nif (isreal(A) ~= 1)\n if (quiet == 0)\n fprintf('A is not real!\\n');\n end\n ret=1;\n return\nend\nif (isreal(b) ~= 1)\n if (quiet == 0)\n fprintf('b is not real!\\n');\n end\n ret=1;\n return\nend\nif (isreal(c) ~= 1)\n if (quiet == 0)\n fprintf('c is not real!\\n');\n end\n ret=1;\n return\nend\n%\n% Check for any quadratic cone constraints.\n%\nif (isfield(K,'q'))\n if ((~isempty(K.q)) & (K.q ~= 0))\n if (quiet == 0)\n fprintf('quadratic cone constraints are not supported.\\n');\n end\n ret=1;\n return\n end\nend \n%\n% Check for any rotated cone constraints.\n%\nif (isfield(K,'r'))\n if ((~isempty(K.r)) & (K.r ~= 0))\n if (quiet == 0)\n fprintf('rotated cone constraints are not supported.\\n');\n end\n ret=1;\n return\n end\nend \n%\n% Check for any free variables.\n%\nif (isfield(K,'f'))\n if ((~isempty(K.f)) & (K.f ~= 0))\n if (quiet == 0)\n fprintf('Free variables are not supported.\\n');\n end\n ret=1;\n return\n end\nend \n%\n% Find the number of constraints.\n%\nm=length(b);\n%\n% Deal with the following special case. If A is transposed, transpose\n% it again so that it is of the right size.\n%\n[Am,An]=size(A);\nif (Am ~= m)\n if (An == m)\n if (quiet==0) \n fprintf('Transposing A to match b \\n');\n end\n AT=A;\n A=A';\n%\n% Also swap Am and An so that they're correct.\n%\n temp=Am;\n Am=An;\n An=temp;\n else\n%\n% In this case, A is just plain the wrong size.\n%\n if (quiet==0)\n fprintf('A is not of the correct size to match b \\n');\n end\n ret=1;\n return\n end\nelse\n%\n% No need to transpose A, but we'll need AT.\n%\n AT=A';\nend\n%\n% Deal with the following special case: if c==0, then c should really\n% be a zero vector of the appropriate size.\n%\nif (c == 0)\n if (quiet==0)\n fprintf('Expanding c to the appropriate size\\n');\n end\n c=sparse(An,1);\nend\n%\n% If c is empty, then act as if it was zero.\n%\nif (isempty(c))\n if (quiet==0)\n fprintf('Expanding empty c to zeros of the appropriate size\\n');\n end\n c=sparse(An,1);\nend\n%\n% If c is a row vector, make it a column vector.\n%\n[cm,cn]=size(c);\nif (cn > cm)\n c=c';\nend\n%\n% Get the size data.\n%\n%\n% First, the size of the LP block.\n%\nif (isfield(K,'l'))\n nlin=K.l;\n sizelin=nlin;\n if (isempty(sizelin))\n sizelin=0;\n nlin=0;\n end\n if (K.l == 0)\n nlin=0;\n sizelin=0;\n end\nelse\n nlin=0;\n sizelin=0;\nend\n%\n% Get the sizes of the SDP blocks.\n%\nif (isfield(K,'s'))\n nsdpblocks=length(K.s);\n sizesdp=sum((K.s).^2);\n if (isempty(sizesdp))\n sizesdp=0;\n nsdpblocks=0;\n end\n if (K.s == 0)\n nsdpblocks=0;\n sizesdp=0;\n end\nelse\n sizesdp=0;\n nsdpblocks=0;\nend\n%\n% Figure out the number of blocks.\n%\nnblocks=nsdpblocks;\nif (nlin>0)\n nblocks=nblocks+1;\nend\n%\n% print out some size information\n%\nif (quiet==0)\n fprintf('Number of constraints: %d \\n',m);\n fprintf('Number of SDP blocks: %d \\n',nsdpblocks);\n fprintf('Number of LP vars: %d \\n',nlin);\nend\n%\n% Open up the file for writing.\n%\nfid=fopen(fname,'w');\nif (fid==-1)\n if (quiet==0)\n fprintf('Could not open file for output!');\n end\n ret=1;\n return\nend\n%\n% Print out m, the number of constraints.\n%\nfprintf(fid,'%d \\n',m);\n%\n% Next, the number of blocks.\n%\nfprintf(fid,'%d \\n',nblocks);\n%\n% Print out the block structure.\n%\nif (K.s > 0)\n fprintf(fid,'%d ',K.s);\nend\nif (nlin > 0)\n fprintf(fid,'%d ',-nlin);\nend\nfprintf(fid,'\\n');\n%\n% Next, b, with all on one line.\n%\nfprintf(fid,'%.18e ',full(b));\nfprintf(fid,'\\n');\n%\n% First, the C matrix.\n%\n%\n% First, calculate where in c things start.\n%\nbase=sizelin+1;\n%\n% Next, work through the SDP blocks.\n%\nfor i=1:nsdpblocks\n%\n% Get the current block of C.\n%\n I=find(c);\n II=find(I>=base);\n I=I(II);\n II=find(I<=base+K.s(i)^2-1);\n I=I(II);\n II=I-(base-1)*ones(size(I));\n work=sparse(II,ones(size(II)),c(I),K.s(i)^2,1);\n work=reshape(work,K.s(i),K.s(i));\n\n%\n% Check this block for symmetry.\n%\nif (norm(work-work','fro') ~= 0)\n if (quiet==0)\n fprintf('Non symmetric C.s matrix!\\n');\n end\n work=(work+work')/2;\nend\n% \n% Write out the C.s matrix. \n%\n work=triu(work);\n [II,JJ,V]=find(work);\n cnt=length(II);\n if (cnt ~= 0)\n fprintf(fid,'%d %d %d %d %.18e\\n',[zeros(size(II)) i*ones(size(II)) II JJ -V]');\n end\n\n%\n% Next, update to the next base.\n%\n base=base+K.s(i)^2;\nend\n%\n% Print out the coefficients for the linear block of C.\n%\nfor i=1:nlin\n if (c(i) ~= 0.0)\n fprintf(fid,'%d %d %d %d %.18e\\n',[0 nsdpblocks+1 i i -full(c(i))]);\n end\nend\n\n%\n% Now, loop through the constraints, one at a time.\n%\nfor cn=1:m\n%\n% Print out the SDP part of constraint cn.\n%\n base=sizelin+1;\n rowcn=AT(:,cn);\n for i=1:nsdpblocks\n I=find(rowcn);\n II=find(I>=base);\n I=I(II);\n II=find(I<=(base+K.s(i)^2-1));\n I=I(II);\n II=I-(base-1)*ones(size(I));\n work=sparse(II,ones(size(II)),rowcn(I),K.s(i)^2,1);\n\n work=reshape(work,K.s(i),K.s(i));\n\n if (norm(work-work','fro') ~= 0)\n if (quiet==0)\n fprintf('Non symmetric A.s matrix! \\n');\n end\n work=(work+work')/2;\n end\n%\n% Ignore the lower left triangle.\n%\n work=triu(work);\n%\n% Get the nonzero entries.\n%\n [II,JJ,V]=find(work);\n cnt=length(II);\n if (cnt ~= 0)\n fprintf(fid,'%d %d %d %d %.18e\\n',[cn*ones(size(II)) i*ones(size(II)) II JJ V]');\n end\n%\n% Next, update to the next base.\n%\n base=base+K.s(i)^2;\n end\n%\n% Finally, the linear part.\n%\n I=find(rowcn);\n II=find(I<=nlin);\n I=I(II);\n workrow=sparse(I,ones(size(I)),rowcn(I),nlin,1);\n [II,JJ,V]=find(workrow);\n if (length(II) > 0)\n fprintf(fid,'%d %d %d %d %.18e\\n',[cn*ones(length(II),1) (nsdpblocks+1)*ones(length(II),1) II II V]');\n end\nend\n%\n% Close the file.\n%\nfclose(fid);\n%\n% Return success\n%\nret=0;\nreturn\n", "meta": {"author": "tobyma2020", "repo": "cluster", "sha": "c9c3706523859f8c34f9741be94fb2dd89fa4cc0", "save_path": "github-repos/MATLAB/tobyma2020-cluster", "path": "github-repos/MATLAB/tobyma2020-cluster/cluster-c9c3706523859f8c34f9741be94fb2dd89fa4cc0/dr/drtoolbox/techniques/writesdpa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.39975629619724684}}
{"text": "% gammaScanScript\nglobal planC\nindexS = planC{end};\n\n[newXgrid, newYgrid, newZgrid] = getScanXYZVals(planC{indexS.scan}(1));\ndeltaX = abs(newXgrid(2) - newXgrid(1));\ndeltaY = abs(newYgrid(2) - newYgrid(1));\ndeltaZ = abs(newZgrid(2) - newZgrid(1));\ndoseAgreement = 15;\ndistAgreement = 0.3;\nthresholdAbsolute = 4000;\ndoseArray1 = single(planC{indexS.scan}(1).scanArray);\ndoseArray2 = single(planC{indexS.scan}(2).scanArray);\ngammaM = gammaDose3d(doseArray1, doseArray2, [deltaX deltaY deltaZ], doseAgreement, distAgreement, [], thresholdAbsolute);\n\nnewDoseNum = length(planC{indexS.dose}) + 1;\n%Remove old caching info.\nplanC{indexS.dose}(newDoseNum).cachedMask = [];\nplanC{indexS.dose}(newDoseNum).cachedColor = [];\nplanC{indexS.dose}(newDoseNum).cachedTime = [];\n%Set coordinates.\nplanC{indexS.dose}(newDoseNum).sizeOfDimension1 = length(newXgrid);\nplanC{indexS.dose}(newDoseNum).sizeOfDimension2 = length(newYgrid);\nplanC{indexS.dose}(newDoseNum).sizeOfDimension3 = length(newZgrid);\nplanC{indexS.dose}(newDoseNum).horizontalGridInterval = newXgrid(2)-newXgrid(1);\nplanC{indexS.dose}(newDoseNum).verticalGridInterval = newYgrid(2)-newYgrid(1);\nplanC{indexS.dose}(newDoseNum).depthGridInterval = newZgrid(2)-newZgrid(1);\nplanC{indexS.dose}(newDoseNum).coord1OFFirstPoint = newXgrid(1);\nplanC{indexS.dose}(newDoseNum).coord2OFFirstPoint = newYgrid(1);\nplanC{indexS.dose}(newDoseNum).coord3OfFirstPoint = newZgrid(1);\nplanC{indexS.dose}(newDoseNum).zValues = newZgrid;\nplanC{indexS.dose}(newDoseNum).doseUnits = 'Gy';\nplanC{indexS.dose}(newDoseNum).doseArray = gammaM;\nplanC{indexS.dose}(newDoseNum).doseUID = createUID('dose');\nplanC{indexS.dose}(newDoseNum).fractionGroupID = 'Gamma Scan 4mm, 50HU';\n%Switch to new dose\nsliceCallBack('selectDose', num2str(newDoseNum));\n\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/Utilities/gammaScanScript.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8056322076481139, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.39966916703726385}}
{"text": "function r = gen_rand_hash(k,n,m);\npersistent buffer\npersistent loc\ntry\n % Preallocate 100 samples everytime and empty that buffer first\n if isempty(buffer) || length(buffer) < loc + n*m\n % Previous approach does not work with parallell toolbox!\n s = rng;\n rng(k);\n buffer = rand(n*m+100,1);\n r = reshape(buffer(1:n*m),n,m);\n loc = 1;\n rng(s);\n end\n r = reshape(buffer(loc:n*m+loc-1),n,m);\n loc = loc + n*m;\n \ncatch\n % but rng is not available in all versions...\n s = rand('state');\n rand('state',k)\n r = rand(n,m);\n rand('state',s);\nend", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/extras/gen_rand_hash.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.39965098268500965}}
{"text": "classdef HomogVoigtPlaneStressHomogenizer < SequentialLaminateHomogenizer\n\n properties (Access = private)\n end\n\n methods (Access = public)\n\n function obj = HomogVoigtPlaneStressHomogenizer(c0,c1,dir,mi,theta)\n obj.init(c0,c1,dir,mi,theta);\n obj.computeAnisotropicTensors();\n obj.homogenize()\n obj.transformToVoigt()\n obj.makeHomogenizedTensorPlaneStress();\n end\n end\n\n methods (Access = protected)\n\n function transformToVoigt(obj)\n t = obj.homogTensor;\n t = Tensor2VoigtConverter.convert(t);\n obj.homogTensor = t;\n end\n\n end\n\n\nend\n\n", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/Topology Optimization/Homogenization/Sources/Homogenizer/SequentialLaminateHomogenizers/HomogVoigtPlaneStressHomogenizer.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7577943712746407, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.39959749329714844}}
{"text": "function varargout = pivotplot(varargin)\n%PIVOTPLOT Semilogy plot of pivot values.\n% PIVOTPLOT( F ) semilogy plot related to the pivots values taken during\n% the construction of the CHEBFUN2 F.\n%\n% H = PIVOTPLOT( F ) returns a handle H to the figure.\n%\n% PIVOTPLOT( F, S ) allows further plotting options, such as linestyle,\n% linecolor, etc. If S contains a string 'LOGLOG', the pseudo sig will be\n% displayed on a log-log scale.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n[varargout{1:nargout}] = pivotplot@separableApprox(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/@chebfun2/pivotplot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.3995974904127376}}
{"text": "function neg_base_exponent(base)\n%\n%\n%\nglobal C\nC = 0;\n\nfigure;\nset(gcf,'position',[350 400 850 350])\n\nsubplot(1,2,1);\nset(gcf,'windowButtonMotionFcn',@fun_mouseMove)\nline([-3 3],[0 0],'color','k','linewidth',3)\n\n\nfunction fun_mouseMove (object, eventdata)\n\nC = get(gca, 'CurrentPoint');\ntitle(gca, ['(X,Y) = (', num2str(C(1,1)), ', ',num2str(C(1,2)), ')']);\n\nsubplot(1,2,2);\ny = base.^C(1,1);\nplot(real(y), imag(y),'ro');\n\nxlim([-5 5])\nylim([-5 5])\n\nend\n\nend\n", "meta": {"author": "angeloyeo", "repo": "gongdols", "sha": "7be9fbd988dec6edab1dc881cb22d63e6f69398d", "save_path": "github-repos/MATLAB/angeloyeo-gongdols", "path": "github-repos/MATLAB/angeloyeo-gongdols/gongdols-7be9fbd988dec6edab1dc881cb22d63e6f69398d/\uae30\ucd08\uc218\ud559/\ubc11\uc774_\uc74c\uc218\uc778_\uc9c0\uc218\ud568\uc218\uc758_\uc2dc\uac01\ud654/neg_base_exponent.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": "function navego_nav2csv(nav)\n% navego_nav2csv: exports navigation data to a .csv file.\n%\n% INPUT\n% nav, INS/GNSS estimations.\n%\n% OUTPUT\n%\t.csv file, with the following columns: time (seconds), roll (deg), \n% pitch (deg), yaw (deg), vel N (m/s), vel E (m/s), vel D (m/s),\n% latitude (deg), longitud (deg), altitude (m). \n%\n% Copyright (C) 2014, Rodrigo Gonzalez, all rights reserved.\n%\n% This file is part of NaveGo, an open-source MATLAB toolbox for\n% simulation of integrated navigation systems.\n%\n% NaveGo is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License (LGPL)\n% version 3 as published by the Free Software Foundation.\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 Lesser General Public License for more details.\n%\n% You should have received a copy of the GNU Lesser General Public\n% License along with this program. If not, see\n% .\n%\n% References:\n%\n%\n% Version: 002\n% Date: 2021/12/09\n% Author: Rodrigo Gonzalez \n% URL: https://github.com/rodralez/navego\n\nR2D = (180/pi); % Radians to degrees\n\n% File name\nif(is_octave)\n dtime = datestr(date, 'yymmdd_HHMMSS' ); \nelse\n dtime = datetime('now','TimeZone','local','Format','yyMMdd-HHmm');\nend\n\nfile_name = sprintf('navego_%s.csv', dtime);\n \n% Headline\nht = 'time (seconds), ';\nha = 'roll (deg), pitch (deg), yaw (deg), ';\nhv = 'vel N (m/s), vel E (m/s), vel D (m/s), ';\nhp = 'latitude (deg), longitud (deg), altitude (m),';\n\n% Navigation data\nnav_data = [nav.t nav.roll*R2D nav.pitch*R2D nav.yaw*R2D ...\n nav.vel(:,1) nav.vel(:,2) nav.vel(:,3) ...\n nav.lat*R2D nav.lon*R2D nav.h ]' ;\n\n% Navigation data precision to be saved\npt = '%.6f, ';\npa = repmat('%.3f, ', 1, 3); \npv = repmat('%.3f, ', 1, 3); \npp = repmat('%.7f, ', 1, 2);\nph = '%.3f, ';\nformat_pattern = [pt pa pv pp ph '\\n']; \n\n% Saving the .cvs file\nfprintf('navego_nav2cvs: saving navigation data to file %s ... \\n', file_name)\n\nfd = fopen(file_name, 'w');\n\n% Saving headline\nfprintf(fd, '%s%s%s%s \\n', ht, ha, hv, hp);\n\n% Saving data\nfprintf(fd, format_pattern , nav_data ); \n \nfclose(fd);\n\nend", "meta": {"author": "rodralez", "repo": "NaveGo", "sha": "3de9a74ab1597be13255d4649892e68aeff9a8b7", "save_path": "github-repos/MATLAB/rodralez-NaveGo", "path": "github-repos/MATLAB/rodralez-NaveGo/NaveGo-3de9a74ab1597be13255d4649892e68aeff9a8b7/performance-analysis/navego_nav2csv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3994874076196448}}
{"text": "% navego_example_real_mpu6000: post-processing integration of MPU-6000 \n% IMU and Ekinox GNSS data.\n%\n% The main goal is to integrate MPU-6000 IMU and Ekinox-D GNSS measurements.\n%\n% Sensors dataset was generated driving a car through the streets of \n% Turin city (Italy).\n%\n% Copyright (C) 2014, Rodrigo Gonzalez, all rights reserved.\n%\n% This file is part of NaveGo, an open-source MATLAB toolbox for\n% simulation of integrated navigation systems.\n%\n% NaveGo is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License (LGPL)\n% version 3 as published by the Free Software Foundation.\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 Lesser General Public License for more details.\n%\n% You should have received a copy of the GNU Lesser General Public\n% License along with this program. If not, see\n% .\n%\n% References:\n%\n% SBG Systems. SBG Ekinox-D High Accuracy Inertial System Brochure, \n% Tactical grade MEMS Inertial Systems, v1.0. February 2014. \n%\n% InvenSense Inc. MPU-6000/MPU-6050 Product Specification. Document \n% Number: PS-MPU-6000A-00. Revision: 3.4. Release Date: 08/19/2013.\n%\n% R. Gonzalez and P. Dabove. Performance Assessment of an Ultra Low-Cost \n% Inertial Measurement Unit for Ground Vehicle Navigation. Sensors 2019, \n% 19(18). https://www.mdpi.com/530156.\n%\n% Version: 006\n% Date: 2021/12/08\n% Author: Rodrigo Gonzalez \n% URL: https://github.com/rodralez/navego\n\n% NOTE: NaveGo assumes that IMU is aligned with respect to body-frame as\n% X-forward, Y-right and Z-down.\n%\n% NOTE: NaveGo assumes that yaw angle (heading) is positive clockwise.\n\nclc\nclose all\nclear\nmatlabrc\n\naddpath ../../ins/\naddpath ../../ins-gnss/\naddpath ../../conversions/\naddpath ../../performance-analysis/\naddpath ../../misc/\naddpath ../../plot/\n\nnavego_print_version;\n\nfprintf('\\nNaveGo: starting real INS/GNSS integration... \\n')\n\n%% PARAMETERS\n\n% Comment any of the following parameters in order to NOT execute a \n% particular portion of code\n\nINS_GNSS = 'ON';\nPLOT = 'ON';\n\nif (~exist('INS_GNSS','var')), INS_GNSS = 'OFF'; end\nif (~exist('PLOT','var')), PLOT = 'OFF'; end\n\n%% CONVERSION CONSTANTS\n\nG = 9.80665; % Gravity constant, m/s^2\nG2MSS = G; % g to m/s^2\nMSS2G = (1/G); % m/s^2 to g\n\nD2R = (pi/180); % degrees to radians\nR2D = (180/pi); % radians to degrees\n\nKT2MS = 0.514444; % knot to m/s\nMS2KMH = 3.6; % m/s to km/h\n\n%% REF DATA\n\n% Reference dataset was obtained by processing Ekinox IMU and Ekinox GNSS \n% with tighly-coupled integration by Inertial Explorer software package.\n\nfprintf('NaveGo: loading reference data... \\n')\n\nload ref\n\n%% MPU-6000 IMU \n\nfprintf('NaveGo: loading MPU-6000 IMU data... \\n')\n\nload mpu6000_imu\n\n%% EKINOX GNSS \n\nfprintf('NaveGo: loading Ekinox GNSS data... \\n')\n\nload ekinox_gnss\n\n% ekinox_gnss contains the lever arm with respect to Ekinox IMU.\n% ekinox_gnss.larm has to be changed for MPU-6000 IMU.\nekinox_gnss.larm = [-0.369, 0.0, -0.219]'; \n\nekinox_gnss.eps = mean(diff(mpu6000_imu.t)) / 2; % A rule of thumb for choosing eps.\n\n%% NAVIGATION TIME\n\nto = (ref.t(end) - ref.t(1));\n\nfprintf('NaveGo: navigation time is %.2f minutes or %.2f seconds. \\n', (to/60), to)\n\n%% INS/GNSS INTEGRATION\n\nif strcmp(INS_GNSS, 'ON')\n \n fprintf('NaveGo: processing INS/GNSS integration... \\n')\n \n % Execute INS/GNSS integration\n % ---------------------------------------------------------------------\n nav_mpu6000 = ins_gnss(mpu6000_imu, ekinox_gnss, 'dcm');\n % ---------------------------------------------------------------------\n \n save nav_mpu6000.mat nav_mpu6000 \nelse\n \n load nav_mpu6000\nend\n\n%% TRAVELED DISTANCE\n\ndistance = gnss_distance (nav_mpu6000.lat, nav_mpu6000.lon);\n\nfprintf('NaveGo: distance traveled by the vehicle is %.2f meters or %.2f km. \\n', distance, distance/1000)\n\n%% ANALYSIS OF PERFORMANCE FOR A CERTAIN PART OF THE INS/GNSS DATASET\n\ntmin_rmse = ref.t(1); \ntmax_rmse = ref.t(end); \n\n% Sincronize REF data to tmin and tmax\nidx = find(ref.t > tmin_rmse, 1, 'first' );\nfdx = find(ref.t < tmax_rmse, 1, 'last' );\nif(isempty(idx) || isempty(fdx))\n error('ref: empty index')\nend\n\nref.t = ref.t (idx:fdx);\nref.roll = ref.roll (idx:fdx);\nref.pitch = ref.pitch(idx:fdx);\nref.yaw = ref.yaw (idx:fdx);\nref.lat = ref.lat (idx:fdx);\nref.lon = ref.lon (idx:fdx);\nref.h = ref.h (idx:fdx);\nref.vel = ref.vel (idx:fdx, :);\n\n%% INTERPOLATION OF INS/GNSS DATASET\n\n% INS/GNSS estimates and GNSS data are interpolated according to the\n% reference dataset.\n\n[nav_i, ref_n] = navego_interpolation (nav_mpu6000, ref);\n[gnss_i, ref_g] = navego_interpolation (ekinox_gnss, ref);\n\n%% NAVIGATION RMSE \n\nrmse_v = print_rmse (nav_i, gnss_i, ref_n, ref_g, 'MPU-6000 INS/GNSS');\n\n%% RMSE TO CVS FILE\n\ncsvwrite('mpu6000.csv', rmse_v);\n\n%% NAVIGATION DATA TO CSV FILE\n\nfprintf('\\n');\nnavego_nav2csv(nav_mpu6000); \n\n%% PLOTS\n\nif (strcmp(PLOT,'ON'))\n \n navego_plot_main (ref, ekinox_gnss, nav_mpu6000, gnss_i, nav_i, ref_g, ref_n)\nend\n\n%% PERFORMANCE ANAYSYS OF THE KALMAN FILTER\n\nfprintf('\\nNaveGo: Kalman filter performance analysis...\\n') \n\nkf_analysis (nav_mpu6000)\n\n", "meta": {"author": "rodralez", "repo": "NaveGo", "sha": "3de9a74ab1597be13255d4649892e68aeff9a8b7", "save_path": "github-repos/MATLAB/rodralez-NaveGo", "path": "github-repos/MATLAB/rodralez-NaveGo/NaveGo-3de9a74ab1597be13255d4649892e68aeff9a8b7/examples/real-data/navego_example_real_mpu6000.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3994874076196448}}
{"text": "\n\n\nHEURISTICS = 0;\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n% Normalize %\n%%%%%%%%%%%%%%%%%%%%%%%%\n\nNormalize = @(x) (x - min(x(:)))/(max(x(:)) - min(x(:)));\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input images %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Img = 'lena';\nImg = 'clena';\n\n switch lower(Img)\n\n case{'lena'}\n Ig = double( imread('gray_imgs/lena_gray_512.png') ) / 255;\n\n case{'peppers'}\n Ig = double( imread('gray_imgs/peppers_gray.png') ) / 255;\n\n case{'goldhl.'}\n Ig = double( imread('gray_imgs/goldhill_gray.png') ) / 255;\n\n case{'clena'}\n Ig = double( imread('color_imgs/lena_color_512.png') ) / 255;\n\n case{'none'}\n disp(' ');\n disp('Select a test image (see code for an example)...');\n disp(' ');\n disp('Exiting test_adaptL1 code...');\n return;\n\n otherwise\n error('Not a valid image\\n');\n\n end\n\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % noisy images %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n Ig_01L1 = imnoise(Ig, 'salt & pepper', 0.1);\n Ig_02L1 = imnoise(Ig, 'salt & pepper', 0.2);\n Ig_03L1 = imnoise(Ig, 'salt & pepper', 0.3);\n Ig_05L1 = imnoise(Ig, 'salt & pepper', 0.5);\n Ig_07L1 = imnoise(Ig, 'salt & pepper', 0.7);\n Ig_09L1 = imnoise(Ig, 'salt & pepper', 0.9);\n\n\n\n Ig_05L2 = imnoise(Ig,'gaussian', 0, ((5/255)^2) );\n Ig_10L2 = imnoise(Ig,'gaussian', 0, ((10/255)^2) );\n Ig_20L2 = imnoise(Ig,'gaussian', 0, ((20/255)^2) );\n Ig_30L2 = imnoise(Ig,'gaussian', 0, ((30/255)^2) );\n\n InCell{1} = imnoise(Ig_10L2, 'salt & pepper', 0.2);\n InCell{2} = imnoise(Ig_20L2, 'salt & pepper', 0.2);\n InCell{3} = imnoise(Ig_30L2, 'salt & pepper', 0.2);\n InCell{4} = imnoise(Ig_10L2, 'salt & pepper', 0.4);\n\n % -----------\n\n InCell{5} = imnoise(Ig_05L2, 'salt & pepper', 0.3);\n InCell{6} = imnoise(Ig_05L2, 'salt & pepper', 0.5);\n\n InCell{7} = imnoise(Ig_10L2, 'salt & pepper', 0.3);\n InCell{8} = imnoise(Ig_10L2, 'salt & pepper', 0.5);\n\n% snr_noisy12 = snr(Ig, In);\n\n% figure; imagesc( Normalize(In) ); \n% axis image; axis off; colormap gray;\n% title(sprintf('Noisy - L1/L2. SNR: %4.1fdB.\\n ', ...\n% snr_noisy12));\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% pre-processing\n\nInputDims = size(Ig);\n\nif(length(InputDims) == 2)\n lambdaS_l2 = [ 0.0185, 0.03, 0.045, 0.0185, 0.0075, 0.0075, 0.0185, 0.0185 ];\nelse\n lambdaS_l2 = 1.5*[ 0.0185, 0.03, 0.045, 0.0185, 0.0075, 0.0075, 0.0185, 0.0185 ];\nend\n\n\nfor k=1:length(InCell)\n\nIn = InCell{k};\n\n tstart = tic;\n\nS0 = adaptMedian(In);\n\nif(length(InputDims) == 2)\n\n if(HEURISTICS)\n lambda_l1l2(:,:,1) = 0.85*(S0 == 3) + ...\n 1.1*(S0 == 5) + 1.2*(S0 == 7) + 1.4*(S0 == 9);\n else\n lambda_l1l2(:,:,1) = 1.5*(S0 ~= 0);\n end\n\n lambda_l1l2(:,:,2) = lambdaS_l2(k)*(S0==0);\n\n planes=1;\nelse\n\n if(HEURISTICS)\n\n for d=1:InputDims(3),\n lambda_l1l2(:,:,d) = 1.05*(S0(:,:,d) == 3) + ...\n 1.3*(S0(:,:,d) == 5) + 1.4*(S0(:,:,d) == 7) + 1.6*(S0(:,:,d) == 9);\n end\n else\n\n for d=1:InputDims(3),\n lambda_l1l2(:,:,d) = 1.75*(S0(:,:,d) ~= 0);\n end\n end\n\n for d=1:InputDims(3),\n lambda_l1l2(:,:,3+d) = lambdaS_l2(k)*(S0(:,:,d)==0);\n end\n\n planes=3;\nend\n\n% ---------- Setup for IRN_L1L2 ------------------\n\npars_irn_adapt = irntvInputPars('l1tv_l2tv');\n\npars_irn_adapt.adapt_epsR = 1;\npars_irn_adapt.epsR_cutoff = 0.01;\npars_irn_adapt.adapt_epsF = 1;\npars_irn_adapt.epsF_cutoff = 0.05;\n\npars_irn_adapt.pcgtol_ini = 1e-4;\n\npars_irn_adapt.loops = 1;\n\npars_irn_adapt.U0 = In; % necessary the for adapt case\n% pars_irn_adapt.U0 = lmu; % necessary the for adapt case\n\n\n Ig_L1L2 = irntv(In, {}, lambda_l1l2, pars_irn_adapt);\n\n\nloops = 6;\n% \nfor m = 2:loops\n \n for d=1:InputDims(3)\n lambda_l1l2(:,:,3+d) = (0.975^(m-1))*lambda_l1l2(:,:,3+d);\n end\n Ipass = Ig_L1L2; \n dI = Ipass - In; \n lambda_l1l2(:,:,1:planes) = adaptLambda(dI, lambda_l1l2(:,:,1:planes), 0.5, S0, 0.8); \n pars_irn_adapt.U0 = Ipass;\n Ig_L1L2 = irntv(In, {}, lambda_l1l2, pars_irn_adapt);\n\nend\nl1l2_time(k) = toc(tstart)\n% \nfigure; imagesc( Normalize(Ig_L1L2) ); axis image; axis off; colormap gray; \n\npsnr_l1l2(k) = psnr(Ig, Ig_L1L2)\n\n\nend\n\npsnr_bing = [32.84, 30.23, 27.33, 29.96]; \npsnr_xiao = [36.20, 33.93, 33.19, 31.51];\n\n[ psnr_l1l2' [psnr_bing'; psnr_xiao']]", "meta": {"author": "xingchenzhang", "repo": "VIFB", "sha": "7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa", "save_path": "github-repos/MATLAB/xingchenzhang-VIFB", "path": "github-repos/MATLAB/xingchenzhang-VIFB/VIFB-7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa/methods/GTF/source/test_snpG.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3994874076196448}}
{"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": "function y = vl_nnreshape(x, shape, varargin)\n% VL_NNRESHAPE Feature reshaping\n% Y = VL_NNRESHAPE(X, SHAPE) reshpaes the input data X to have\n% the dimensions specified by SHAPE. X is a SINGLE array of\n% dimension H x W x D x N where (H,W) are the height and width of\n% the map stack, D is the image depth (number of feature channels)\n% and N the number of of images in the stack. SHAPE is a 1 x 3 cell\n% array, the contents of which are passed in order to the MATLAB\n% reshape function. As a consequence, `[]` an be used to specify a\n% dimension which should be computed from the other two. The batch size\n% (the fourth dimension of the input) is left unchanged by this\n% reshaping operation.\n%\n% Alternatively, SHAPE can be specified in the \"caffe style\", as an\n% array, using `0` to indicate that a dimension should be preserved and\n% `-1` to indicate a dimension that should be computed from the others\n% (this serves the same role as [] in the standard MATLAB convention).\n%\n% Example:\n% Inputs: X with shape [100 100 3 5] and SHAPE = { 100 3 [] }\n% will produce an output Y with shape [100 3 100 5]\n%\n% DZDX = VL_NNRESHAPE(X, SHAPE, DZDY) computes the derivatives of the\n% block projected onto DZDY. DZDX and DZDY have the same dimensions\n% as X and Y respectively.\n%\n% Copyright (C) 2017 Samuel Albanie and Andrea Vedaldi.\n% Licensed under The MIT License [see LICENSE.md for details]\n\n [~, dzdy] = vl_argparsepos(struct(), varargin) ;\n\n if isnumeric(shape) % apply caffe style conventions if needed\n shape_ = num2cell(shape) ;\n if numel(shape_) == 2, shape_{3} = [] ; end\n k = find(shape == -1) ; if k, shape_{k} = [] ; end\n k = find(shape == 0) ;\n if k, rep = arrayfun(@(i) {size(x,i)}, k) ; shape_(k) = rep ; end\n shape = shape_ ;\n end\n\n batchSize = size(x, 4);\n\n if isempty(dzdy)\n y = reshape(x, shape{1}, shape{2}, shape{3}, batchSize) ;\n else\n y = reshape(dzdy{1}, size(x)) ;\n end\n", "meta": {"author": "ShuaiBai623", "repo": "MFT", "sha": "8762f8cdf494ce0b1a1c3d431660c5c8fd91744a", "save_path": "github-repos/MATLAB/ShuaiBai623-MFT", "path": "github-repos/MATLAB/ShuaiBai623-MFT/MFT-8762f8cdf494ce0b1a1c3d431660c5c8fd91744a/external_libs/matconvnet/contrib/mcnExtraLayers/matlab/vl_nnreshape.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370111, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.39948740761964474}}
{"text": "function varargout = WFTKernel(varargin)\n% Function: Windowed Fourier transofmr (Kernel)\n% Initially Developed: Dr Qian Kemao (16 May 2009)\n% Last modified: Dr Qian Kemao (17 May 2009)\n% Version: 1.0\n% Copyrights: All rights reserved.\n% Contact: mkmqian@ntu.edu.sg (Dr Qian Kemao)\n\n%WFTKERNEL M-file for WFTKernel.fig\n% WFTKERNEL, by itself, creates a new WFTKERNEL or raises the existing\n% singleton*.\n%\n% H = WFTKERNEL returns the handle to a new WFTKERNEL or the handle to\n% the existing singleton*.\n%\n% WFTKERNEL('Property','Value',...) creates a new WFTKERNEL using the\n% given property value pairs. Unrecognized properties are passed via\n% varargin to WFTKernel_OpeningFcn. This calling syntax produces a\n% warning when there is an existing singleton*.\n%\n% WFTKERNEL('CALLBACK') and WFTKERNEL('CALLBACK',hObject,...) call the\n% local function named CALLBACK in WFTKERNEL.M with the given input\n% arguments.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Edit the above text to modify the response to help WFTKernel\n\n% Last Modified by GUIDE v2.5 16-May-2009 10:09:25\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @WFTKernel_OpeningFcn, ...\n 'gui_OutputFcn', @WFTKernel_OutputFcn, ...\n 'gui_LayoutFcn', [], ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before WFTKernel is made visible.\nfunction WFTKernel_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin unrecognized PropertyName/PropertyValue pairs from the\n% command line (see VARARGIN)\n\n% Choose default command line output for WFTKernel\nhandles.output = hObject;\n\n% Update handles structure\nguidata(hObject, handles);\n\n% UIWAIT makes WFTKernel wait for user response (see UIRESUME)\n% uiwait(handles.figure1);\n\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = WFTKernel_OutputFcn(hObject, eventdata, handles)\n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\n\n\nfunction edit_sigmax_Callback(hObject, eventdata, handles)\n% hObject handle to edit_sigmax (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit_sigmax as text\n% str2double(get(hObject,'String')) returns contents of edit_sigmax as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit_sigmax_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit_sigmax (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction edit_wxl_Callback(hObject, eventdata, handles)\n% hObject handle to edit_wxl (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit_wxl as text\n% str2double(get(hObject,'String')) returns contents of edit_wxl as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit_wxl_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit_wxl (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction edit_wxi_Callback(hObject, eventdata, handles)\n% hObject handle to edit_wxi (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit_wxi as text\n% str2double(get(hObject,'String')) returns contents of edit_wxi as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit_wxi_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit_wxi (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction edit_wxh_Callback(hObject, eventdata, handles)\n% hObject handle to edit_wxh (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit_wxh as text\n% str2double(get(hObject,'String')) returns contents of edit_wxh as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit_wxh_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit_wxh (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction edit_sigmay_Callback(hObject, eventdata, handles)\n% hObject handle to edit_sigmay (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit_sigmay as text\n% str2double(get(hObject,'String')) returns contents of edit_sigmay as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit_sigmay_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit_sigmay (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction edit_wyl_Callback(hObject, eventdata, handles)\n% hObject handle to edit_wyl (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit_wyl as text\n% str2double(get(hObject,'String')) returns contents of edit_wyl as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit_wyl_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit_wyl (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction edit_wyi_Callback(hObject, eventdata, handles)\n% hObject handle to edit_wyi (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit_wyi as text\n% str2double(get(hObject,'String')) returns contents of edit_wyi as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit_wyi_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit_wyi (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction edit_wyh_Callback(hObject, eventdata, handles)\n% hObject handle to edit_wyh (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit_wyh as text\n% str2double(get(hObject,'String')) returns contents of edit_wyh as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit_wyh_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit_wyh (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction edit_thr_Callback(hObject, eventdata, handles)\n% hObject handle to edit_thr (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit_thr as text\n% str2double(get(hObject,'String')) returns contents of edit_thr as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit_thr_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit_thr (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on button press in push_WFTRun.\nfunction push_WFTRun_Callback(hObject, eventdata, handles)\n% hObject handle to push_WFTRun (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nload result\nH=findobj('Tag','radiobutton_wff'); val=get(H,'Value');\nif val==1\n g.AlgorithmType='wff';\nelse\n g.AlgorithmType='wfr';\nend\nH=findobj('Tag','edit_sigmax'); sigmax=str2num(get(H,'String'));\nH=findobj('Tag','edit_sigmax'); sigmax=str2num(get(H,'String'));\nH=findobj('Tag','edit_wxl'); wxl=str2num(get(H,'String'));\nH=findobj('Tag','edit_wxi'); wxi=str2num(get(H,'String'));\nH=findobj('Tag','edit_wxh'); wxh=str2num(get(H,'String'));\nH=findobj('Tag','edit_sigmay'); sigmay=str2num(get(H,'String'));\nH=findobj('Tag','edit_wyl'); wyl=str2num(get(H,'String'));\nH=findobj('Tag','edit_wyi'); wyi=str2num(get(H,'String'));\nH=findobj('Tag','edit_wyh'); wyh=str2num(get(H,'String'));\nH=findobj('Tag','edit_thr'); thr=str2num(get(H,'String'));\ng0=wft2fw(g.AlgorithmType,g.f,sigmax,wxl,wxi,wxh,sigmay,wyl,wyi,wyh,thr);\nif strcmp(g.AlgorithmType,'wff')\n g.filtered=g0.filtered;\nelse\n g.wx=g0.wx;\n g.wy=g0.wy;\n g.r=g0.r;\n g.phase=g0.phase;\n g.filtered=g.r.*exp(sqrt(-1)*g.phase);\nend\nsave result g;\nH=findobj('Name','Windowed Fourier Transform (WFT)');figure(H);imagesc(angle(g.filtered));\nH=findobj('Name','WFT Kernel');close(H);\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/24892-windowed-fourier-transform-for-fringe-pattern-analysis-with-gui/WFTgui/WFTKernel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.7057850216484839, "lm_q1q2_score": 0.3994874041168236}}
{"text": "% LFDecodeLensletImageSimple - decodes a 2D lenslet image into a 4D light field, called by LFUtilDecodeLytroFolder\n%\n% Usage:\n%\n% [LF, LFWeight, DecodeOptions, DebayerLensletImage, CorrectedLensletImage] = ...\n% LFDecodeLensletImageSimple( LensletImage, WhiteImage, LensletGridModel, DecodeOptions )\n%\n% This function follows the simple decode process described in:\n% D. G. Dansereau, O. Pizarro, and S. B. Williams, \"Decoding, calibration and rectification for\n% lenslet-based plenoptic cameras,\" in Computer Vision and Pattern Recognition (CVPR), IEEE\n% Conference on. IEEE, Jun 2013.\n%\n% This involves demosaicing, devignetting, transforming and slicing the input lenslet image to\n% yield a 4D structure. More sophisticated approaches exist which combine steps into joint\n% solutions, and they generally yield superior results, particularly near the edges of lenslets.\n% The approach taken here was chosen for its simplicity and flexibility.\n%\n% Input LensletImage is a raw lenslet iamge as found within Lytro's LFP picture files. Though\n% this function is written with Lytro imagery in mind, it should be possible to adapt it for use\n% with other lenslet-based cameras. LensletImage is ideally of type uint16.\n%\n% Input WhiteImage is a white image as found within Lytro's calibration data. A white image is an\n% image taken through a diffuser, and is useful for removing vignetting (darkening near edges of\n% images) and for locating lenslet centers. The white image should be taken under the same zoom and\n% focus settings as the light field. In the case of Lytro imagery, the helper functions\n% LFUtilProcessWhiteImages and LFSelectFromDatabase are provided to assist in forming a list of\n% available white images, and selecting the appropriate image based on zoom and focus settings.\n%\n% Input LensletGridModel is a model of the lenslet grid, as estimated, for example, using\n% LFBuildLensletGridModel -- see that function for more on the required structure.\n%\n% Optional Input DecodeOptions is a structure containing:\n% [Optional] ResampMethod : 'fast'(default) or 'triangulation', the latter is slower\n% [Optional] Precision : 'single'(default) or 'double'\n% [Optional] LevelLimits : a two-element vector defining the black and white levels\n%\n% Output LF is a 5D array of size [Nj,Ni,Nl,Nk,3]. See [1] and the documentation accompanying this\n% toolbox for a brief description of the light field structure.\n%\n% Optional output LFWeight is of size [Nj,Ni,Nl,Nk]. LFWeight contains a confidence measure\n% suitable for use in filtering applications that accept a weight parameter. This parameter is kept\n% separate from LF rather than building in as a fourth channel in order to allow an optimization:\n% when the parameter is not requested, it is not computed, saving significant processing time and\n% memory.\n%\n% Optional output DebayerLensletImage is useful for inspecting intermediary results. The debayered\n% lenslet image is the result of devignetting and debayering, with no further processing. Omitting\n% this output variable saves memory.\n%\n% Optional output CorrectedLensletImage is useful for inspecting intermediary results. The\n% corrected lenslet image has been rotated and scaled such that lenslet centers lie on straight lines, and\n% every lenslet center lies on an integer pixel spacing. See [1] for more detail. Omitting\n% this output variable saves memory.\n%\n% A more direct version of this function LFDecodeLensletImageDirect does not generate the \n% intermediate corrected lenslet image.\n%\n% User guide: LFToolbox.pdf\n% See also: LFLytroDecodeImage, LFUtilDecodeLytroFolder, LFDecodeLensletImageDirect\n\n% Copyright (c) 2013-2020 Donald G. Dansereau\n\nfunction [LF, LFWeight, DecodeOptions, DebayerLensletImage, CorrectedLensletImage] = ...\n LFDecodeLensletImageSimple( LensletImage, WhiteImage, LensletGridModel, DecodeOptions )\n\n%---Defaults---\n % LevelLimits defaults are a failsafe, should be passed in / come from the white image metadata\nDecodeOptions = LFDefaultField( 'DecodeOptions', 'LevelLimits', [min(WhiteImage(:)), max(WhiteImage(:))] );\nDecodeOptions = LFDefaultField( 'DecodeOptions', 'ResampMethod', 'fast' ); %'fast', 'triangulation'\nDecodeOptions = LFDefaultField( 'DecodeOptions', 'Precision', 'single' );\nDecodeOptions = LFDefaultField( 'DecodeOptions', 'DoDehex', true );\nDecodeOptions = LFDefaultField( 'DecodeOptions', 'DoSquareST', true );\n\n%---Rescale image values, remove black level---\nDecodeOptions.LevelLimits = cast(DecodeOptions.LevelLimits, DecodeOptions.Precision);\nBlackLevel = DecodeOptions.LevelLimits(1);\nWhiteLevel = DecodeOptions.LevelLimits(2);\nWhiteImage = cast(WhiteImage, DecodeOptions.Precision);\nWhiteImage = (WhiteImage - BlackLevel) ./ (WhiteLevel - BlackLevel);\n\nLensletImage = cast(LensletImage, DecodeOptions.Precision);\nLensletImage = (LensletImage - BlackLevel) ./ (WhiteLevel - BlackLevel);\nLensletImage = LensletImage ./ WhiteImage; % Devignette\n% Clip -- this is aggressive and throws away bright areas; there is a potential for an HDR approach here\nLensletImage = min(1, max(0, LensletImage));\n\nif( nargout < 2 )\n clear WhiteImage\nend\n\n%---Demosaic---\n% This uses Matlab's demosaic, which is \"gradient compensated\". This likely has implications near\n% the edges of lenslet images, where the contrast is due to vignetting / aperture shape, and is not\n% a desired part of the image\nLensletImage = cast(LensletImage.*double(intmax('uint16')), 'uint16');\nLensletImage = demosaic(LensletImage, DecodeOptions.DemosaicOrder);\nLensletImage = cast(LensletImage, DecodeOptions.Precision);\nLensletImage = LensletImage ./ double(intmax('uint16'));\nDecodeOptions.NColChans = 3;\n\nif( nargout >= 2 )\n DecodeOptions.NWeightChans = 1;\nelse\n DecodeOptions.NWeightChans = 0;\nend\n\nif( nargout > 3 )\n DebayerLensletImage = LensletImage;\nend\n\n%---Tranform to an integer-spaced grid---\nfprintf('\\nAligning image to lenslet array...');\nInputSpacing = [LensletGridModel.HSpacing, LensletGridModel.VSpacing];\nNewLensletSpacing = ceil(InputSpacing);\n% Force even so hex shift is a whole pixel multiple\nNewLensletSpacing = ceil(NewLensletSpacing/2)*2;\nXformScale = NewLensletSpacing ./ InputSpacing; % Notice the resized image will not be square\n\nNewOffset = [LensletGridModel.HOffset, LensletGridModel.VOffset] .* XformScale;\nRoundedOffset = round(NewOffset);\nXformTrans = RoundedOffset-NewOffset;\n\nNewLensletGridModel = struct('HSpacing',NewLensletSpacing(1), 'VSpacing',NewLensletSpacing(2), ...\n 'HOffset',RoundedOffset(1), 'VOffset',RoundedOffset(2), 'Rot',0, ...\n 'UMax', LensletGridModel.UMax, 'VMax', LensletGridModel.VMax, 'Orientation', LensletGridModel.Orientation, ...\n 'FirstPosShiftRow', LensletGridModel.FirstPosShiftRow);\n\n%---Fix image rotation and scale---\nRRot = LFRotz( LensletGridModel.Rot );\n\nRScale = eye(3);\nRScale(1,1) = XformScale(1);\nRScale(2,2) = XformScale(2);\nDecodeOptions.OutputScale(1:2) = XformScale;\nDecodeOptions.OutputScale(3:4) = [1,2/sqrt(3)]; % hex sampling\n\nRTrans = eye(3);\nRTrans(end,1:2) = XformTrans;\n\n% The following rotation can rotate parts of the lenslet image out of frame.\n% todo[optimization]: attempt to keep these regions, offer greater user-control of what's kept\nFixAll = maketform('affine', RRot*RScale*RTrans);\nNewSize = size(LensletImage(:,:,1)) .* XformScale(2:-1:1);\nLensletImage = imtransform( LensletImage, FixAll, 'YData',[1 NewSize(1)], 'XData',[1 NewSize(2)]);\nif( nargout >= 2 )\n WhiteImage = imtransform( WhiteImage, FixAll, 'YData',[1 NewSize(1)], 'XData',[1 NewSize(2)]);\nend\nif( nargout >= 4 )\n CorrectedLensletImage = LensletImage;\nend\n\nLF = SliceXYImage( NewLensletGridModel, LensletImage, WhiteImage, DecodeOptions );\nclear WhiteImage LensletImage\n\n%---Correct for hex grid and resize to square u,v pixels---\nLFSize = size(LF);\nHexAspect = 2/sqrt(3);\nswitch( DecodeOptions.ResampMethod )\n case 'fast'\n fprintf('\\nResampling (1D approximation) to square u,v pixels');\n NewUVec = 0:1/HexAspect:(size(LF,4)+1); % overshoot then trim\n NewUVec = NewUVec(1:ceil(LFSize(4)*HexAspect));\n OrigUSize = size(LF,4);\n LFSize(4) = length(NewUVec);\n %---Allocate dest and copy orig LF into it (memory saving vs. keeping both separately)---\n LF2 = zeros(LFSize, DecodeOptions.Precision);\n LF2(:,:,:,1:OrigUSize,:) = LF;\n LF = LF2;\n clear LF2\n \n if( DecodeOptions.DoDehex )\n ShiftUVec = -0.5+NewUVec;\n fprintf(' and removing hex sampling...');\n else\n ShiftUVec = NewUVec;\n fprintf('...');\n end\n for( ColChan = 1:size(LF,5) )\n CurUVec = ShiftUVec;\n for( RowIter = 1:2 )\n RowIdx = mod(NewLensletGridModel.FirstPosShiftRow + RowIter, 2) + 1;\n ShiftRows = squeeze(LF(:,:,RowIdx:2:end,1:OrigUSize, ColChan));\n SliceSize = size(ShiftRows);\n SliceSize(4) = length(NewUVec);\n ShiftRows = reshape(ShiftRows, [size(ShiftRows,1)*size(ShiftRows,2)*size(ShiftRows,3), size(ShiftRows,4)]);\n ShiftRows = interp1( (0:size(ShiftRows,2)-1)', ShiftRows', CurUVec' )';\n ShiftRows(isnan(ShiftRows)) = 0;\n LF(:,:,RowIdx:2:end,:,ColChan) = reshape(ShiftRows,SliceSize);\n CurUVec = NewUVec;\n end\n end\n clear ShiftRows\n DecodeOptions.OutputScale(3) = DecodeOptions.OutputScale(3) * HexAspect;\n \n case 'triangulation'\n fprintf('\\nResampling (triangulation) to square u,v pixels');\n OldVVec = (0:size(LF,3)-1);\n OldUVec = (0:size(LF,4)-1) * HexAspect;\n \n NewUVec = (0:ceil(LFSize(4)*HexAspect)-1);\n NewVVec = (0:LFSize(3)-1);\n LFSize(4) = length(NewUVec);\n LF2 = zeros(LFSize, DecodeOptions.Precision);\n \n [Oldvv,Olduu] = ndgrid(OldVVec,OldUVec);\n [Newvv,Newuu] = ndgrid(NewVVec,NewUVec);\n if( DecodeOptions.DoDehex )\n fprintf(' and removing hex sampling...');\n FirstShiftRow = NewLensletGridModel.FirstPosShiftRow;\n Olduu(FirstShiftRow:2:end,:) = Olduu(FirstShiftRow:2:end,:) + HexAspect/2;\n else\n fprintf('...');\n end\n \n DT = delaunayTriangulation( Olduu(:), Oldvv(:) ); % use DelaunayTri in older Matlab versions\n [ti,bc] = pointLocation(DT, Newuu(:), Newvv(:));\n ti(isnan(ti)) = 1;\n \n for( ColChan = 1:size(LF,5) )\n fprintf('.');\n for( tidx= 1:LFSize(1) )\n for( sidx= 1:LFSize(2) )\n CurUVSlice = squeeze(LF(tidx,sidx,:,:,ColChan));\n triVals = CurUVSlice(DT(ti,:));\n CurUVSlice = dot(bc',triVals')';\n CurUVSlice = reshape(CurUVSlice, [length(NewVVec),length(NewUVec)]);\n \n CurUVSlice(isnan(CurUVSlice)) = 0;\n LF2(tidx,sidx, :,:, ColChan) = CurUVSlice;\n end\n end\n end\n LF = LF2;\n clear LF2\n DecodeOptions.OutputScale(3) = DecodeOptions.OutputScale(3) * HexAspect;\n \n otherwise\n fprintf('\\nNo valid dehex / resampling selected\\n');\nend\n\n%---Resize to square s,t pixels---\n% Assumes only a very slight resampling is required, resulting in an identically-sized output light field\nif( DecodeOptions.DoSquareST )\n fprintf('\\nResizing to square s,t pixels using 1D linear interp...');\n \n ResizeScale = DecodeOptions.OutputScale(1)/DecodeOptions.OutputScale(2);\n ResizeDim1 = 1;\n ResizeDim2 = 2;\n if( ResizeScale < 1 )\n ResizeScale = 1/ResizeScale;\n ResizeDim1 = 2;\n ResizeDim2 = 1;\n end\n \n OrigSize = size(LF, ResizeDim1);\n OrigVec = floor((-(OrigSize-1)/2):((OrigSize-1)/2));\n NewVec = OrigVec ./ ResizeScale;\n \n OrigDims = [1:ResizeDim1-1, ResizeDim1+1:5];\n \n UBlkSize = 32;\n USize = size(LF,4);\n LF = permute(LF,[ResizeDim1, OrigDims]);\n for( UStart = 1:UBlkSize:USize )\n UStop = UStart + UBlkSize - 1;\n UStop = min(UStop, USize);\n LF(:,:,:,UStart:UStop,:) = interp1(OrigVec, LF(:,:,:,UStart:UStop,:), NewVec);\n fprintf('.');\n end\n LF = ipermute(LF,[ResizeDim1, OrigDims]);\n LF(isnan(LF)) = 0;\n \n DecodeOptions.OutputScale(ResizeDim2) = DecodeOptions.OutputScale(ResizeDim2) * ResizeScale;\nend\n\n\n%---Trim s,t---\nLF = LF(2:end-1,2:end-1, :,:, :);\n\n%---Slice out LFWeight if it was requested---\nif( nargout >= 2 )\n LFWeight = LF(:,:,:,:,end);\n LFWeight = LFWeight./max(LFWeight(:));\n LF = LF(:,:,:,:,1:end-1);\nend\n\nend\n\n%------------------------------------------------------------------------------------------------------\nfunction LF = SliceXYImage( LensletGridModel, LensletImage, WhiteImage, DecodeOptions )\n% todo[optimization]: The SliceIdx and ValidIdx variables could be precomputed\n\nfprintf('\\nSlicing lenslets into LF...');\n\nUSize = LensletGridModel.UMax;\nVSize = LensletGridModel.VMax;\nMaxSpacing = max(LensletGridModel.HSpacing, LensletGridModel.VSpacing); % Enforce square output in s,t\nSSize = MaxSpacing + 1; % force odd for centered middle pixel -- H,VSpacing are even, so +1 is odd\nTSize = MaxSpacing + 1;\n\nLF = zeros(TSize, SSize, VSize, USize, DecodeOptions.NColChans + DecodeOptions.NWeightChans, DecodeOptions.Precision);\n\nTVec = cast(floor((-(TSize-1)/2):((TSize-1)/2)), 'int16');\nSVec = cast(floor((-(SSize-1)/2):((SSize-1)/2)), 'int16');\nVVec = cast(0:VSize-1, 'int16');\nUBlkSize = 32;\nfor( UStart = 0:UBlkSize:USize-1 ) % note zero-based indexing\n UStop = UStart + UBlkSize - 1;\n UStop = min(UStop, USize-1); \n UVec = cast(UStart:UStop, 'int16');\n \n [tt,ss,vv,uu] = ndgrid( TVec, SVec, VVec, UVec );\n \n %---Build indices into 2D image---\n LFSliceIdxX = LensletGridModel.HOffset + uu.*LensletGridModel.HSpacing + ss;\n LFSliceIdxY = LensletGridModel.VOffset + vv.*LensletGridModel.VSpacing + tt;\n \n HexShiftStart = LensletGridModel.FirstPosShiftRow;\n LFSliceIdxX(:,:,HexShiftStart:2:end,:) = LFSliceIdxX(:,:,HexShiftStart:2:end,:) + LensletGridModel.HSpacing/2;\n \n %---Lenslet mask in s,t and clip at image edges---\n CurSTAspect = DecodeOptions.OutputScale(1)/DecodeOptions.OutputScale(2);\n R = sqrt((cast(tt,DecodeOptions.Precision)*CurSTAspect).^2 + cast(ss,DecodeOptions.Precision).^2);\n ValidIdx = find(R < LensletGridModel.HSpacing/2 & ...\n LFSliceIdxX >= 1 & LFSliceIdxY >= 1 & LFSliceIdxX <= size(LensletImage,2) & LFSliceIdxY <= size(LensletImage,1) );\n \n %--clip -- the interp'd values get ignored via ValidIdx--\n LFSliceIdxX = max(1, min(size(LensletImage,2), LFSliceIdxX ));\n LFSliceIdxY = max(1, min(size(LensletImage,1), LFSliceIdxY ));\n \n %---\n LFSliceIdx = sub2ind(size(LensletImage), cast(LFSliceIdxY,'int32'), ...\n cast(LFSliceIdxX,'int32'), ones(size(LFSliceIdxX),'int32'));\n \n tt = tt - min(tt(:)) + 1;\n ss = ss - min(ss(:)) + 1;\n vv = vv - min(vv(:)) + 1;\n uu = uu - min(uu(:)) + 1 + UStart;\n LFOutSliceIdx = sub2ind(size(LF), cast(tt,'int32'), cast(ss,'int32'), ...\n cast(vv,'int32'),cast(uu,'int32'), ones(size(ss),'int32'));\n \n %---\n for( ColChan = 1:DecodeOptions.NColChans )\n LF(LFOutSliceIdx(ValidIdx) + numel(LF(:,:,:,:,1)).*(ColChan-1)) = ...\n LensletImage( LFSliceIdx(ValidIdx) + numel(LensletImage(:,:,1)).*(ColChan-1) );\n end\n if( DecodeOptions.NWeightChans ~= 0 )\n LF(LFOutSliceIdx(ValidIdx) + numel(LF(:,:,:,:,1)).*(DecodeOptions.NColChans)) = ...\n WhiteImage( LFSliceIdx(ValidIdx) );\n end\n fprintf('.');\nend\nend\n", "meta": {"author": "doda42", "repo": "LFToolbox", "sha": "5dd4a8acf6555ae362a7c5b8d5bd4b9827790a4e", "save_path": "github-repos/MATLAB/doda42-LFToolbox", "path": "github-repos/MATLAB/doda42-LFToolbox/LFToolbox-5dd4a8acf6555ae362a7c5b8d5bd4b9827790a4e/SupportFunctions/LFDecodeLensletImageSimple.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7520125737597971, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.39947612807612753}}
{"text": "function cur_shift = WardGetExpShift(img1, img2, ward_percentile, shift_bits)\n%\n%\n% cur_shift = WardGetExpShift(img1, img2, ward_percentile, shift_bits)\n%\n% This function computes the Ward's MTB.\n%\n% Input:\n% -img1: the target image\n% -img2: the image that needs to be aligned to img1\n%\n% Output:\n% -cur_shift: shifting vector for aligning img2 into img1.\n%\n% Copyright (C) 2012-15 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\nif(~exist('ward_percentile', 'var'))\n ward_percentile = 0.5;\nend\n\nif(~exist('shift_bits', 'var'))\n shift_bits = 6;\nend\n\ncur_shift = zeros(2, 1);\nshift_ret = zeros(2, 1);\n\nwhile(shift_bits > 0)\n %computing MTB\n sml_img1 = imresize(img1, 2^(-shift_bits), 'bilinear');\n sml_img2 = imresize(img2, 2^(-shift_bits), 'bilinear');\n \n [tb1, eb1] = WardComputeThreshold(sml_img1, ward_percentile);\n [tb2, eb2] = WardComputeThreshold(sml_img2, ward_percentile);\n\n min_err = size(sml_img1, 1) * size(sml_img1, 2);\n\n tb1 = logical(tb1);\n eb1 = logical(eb1);\n\n for i=-1:1\n for j=-1:1\n xs = cur_shift(1) + i;\n ys = cur_shift(2) + j;\n\n shifted_tb2 = logical(imShift(tb2, [xs, ys]));\n shifted_eb2 = logical(imShift(eb2, [xs, ys]));\n\n diff_b = bitxor(tb1, shifted_tb2);\n diff_b = diff_b & eb1;\n diff_b = diff_b & shifted_eb2;\n\n err = sum(diff_b(:));\n\n if (err < min_err)\n shift_ret = [xs; ys];\n min_err = err;\n end\n end\n end\n \n shift_bits = shift_bits - 1;\n cur_shift = shift_ret * 2;\nend\n\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/Alignment/util/WardGetExpShift.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.3994405360165211}}
{"text": "function test_suite = test_angle2Points\n%TESTCLIPLINE One-line description here, please.\n% output = testAngle2Points(input)\n%\n% Example\n% testAngle2Points\n%\n% See also\n%\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2009-04-22, using Matlab 7.7.0.471 (R2008b)\n% Copyright 2009 INRA - Cepia Software Platform.\n\ntest_suite = functiontests(localfunctions);\n\nfunction testHoriz(testCase) %#ok<*DEFNU>\n% all points inside window, possibly touching edges\n\np1 = [0 0];\np2 = [10 0];\nangle = angle2Points(p1, p2);\ntestCase.assertEqual(0, angle, 'AbsTol', .01);\n\nangle = angle2Points(p2, p1);\ntestCase.assertEqual(pi, angle, 'AbsTol', .01);\n\nfunction testVert(testCase)\n% all points inside window, possibly touching edges\n\np1 = [0 0];\np2 = [0 10];\nangle = angle2Points(p1, p2);\ntestCase.assertEqual(pi/2, angle, 'AbsTol', .01);\n\nangle = angle2Points(p2, p1);\ntestCase.assertEqual(3*pi/2, angle, 'AbsTol', .01);\n\n\nfunction testMultiMulti(testCase)\n% all points inside window, possibly touching edges\n\np1 = [0 0;0 0;0 0;0 0];\np2 = [10 0;10 10;0 10;-10 10];\nangle = angle2Points(p1, p2);\ntestCase.assertEqual(size(p1, 1), size(angle, 1), 'AbsTol', .01);\n\nres = [0;pi/4;pi/2;3*pi/4];\ntestCase.assertEqual(res, angle, 'AbsTol', .01);\n\nfunction testOneMulti(testCase)\n% all points inside window, possibly touching edges\n\np1 = [0 0];\np2 = [10 0;10 10;0 10;-10 10];\nangle = angle2Points(p1, p2);\ntestCase.assertEqual(size(p2, 1), size(angle, 1), 'AbsTol', .01);\n\nres = [0;pi/4;pi/2;3*pi/4];\ntestCase.assertEqual(res, angle, 'AbsTol', .01);\n\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/tests/geom2d/test_angle2Points.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.3994405360165211}}
{"text": "function d = generate(a)\n\nif a.seed>0 rand('seed',a.seed); end;\nx=(rand(a.l,a.n)-0.5)*2;\nw=ones(1,a.n); \nprem=a.n-min(a.relevant_n,a.n);\nw(1:prem)=0;\ny=sign(x*w');\n\n\n\n\nd=data([get_name(a) ' '] ,x,y);", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/External/spider/basic/@toy/generate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.3994405292411902}}
{"text": "function [coordinate, rgb] = getPointsFromRGBD(RGBDframe)\n\nX = reshape(RGBDframe(:,:,[1 2 3 5 6 4]),[],6)';\nvalid = X(6,:) > 0;\n\ncoordinate = X(4:6,valid);\nrgb = X(1:3,valid);\n", "meta": {"author": "jianxiongxiao", "repo": "ProfXkit", "sha": "7376c50abf5ead846247774a36be026e6f24953c", "save_path": "github-repos/MATLAB/jianxiongxiao-ProfXkit", "path": "github-repos/MATLAB/jianxiongxiao-ProfXkit/ProfXkit-7376c50abf5ead846247774a36be026e6f24953c/depthImproveStructureIO/getPointsFromRGBD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7154239836484143, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.39944052246585926}}
{"text": "function [ Psi ] = buildPsi2( options, psi, configuration )\n%BUILDPSI functions creates vector \\Psi(I, S) for given configuration\n% Detailed explanation goes here\n% \n% INPUT\n% options ... structure holds info about components (size, count) and S (statistics of component position)\n% psi ... cell Mx1 contains matrices \\Psi^q(I, S_i)\n% configuration ... matrix 2xM [x0, ..., x_{M-1}; y_0, ..., y_{M-1}] with positions of components\n% \n% OUTPUT\n% Psi ... vector [\\Psi_0^q(I, S_0); ... ; \\Psi_{M-1}^q(I, S_{M-1}); g(S_0xS_1); ... ; g(S_0xS_{M-1})];\n% \n% 10-08-10 Michal Uricar\n% 11-07-11 Michal Uricar, corners dataset modificatoin\n\n indices = zeros(1, options.M);\n \n Psi = [];\n\n for i = 1 : options.M\n psi_si = psi{i};\n P = configuration(:, i) - [options.S(1, i) - 1; options.S(2, i) - 1];\n siz = [options.S(4, i) - options.S(2, i) + 1; options.S(3, i) - options.S(1, i) + 1];\n indices(i) = (P(1) - 1)*siz(1) + P(2);\n Psi = [Psi; psi_si(:, indices(i))];\n end;\n \n % g\n %for i = 2 : options.M - 2\n for i = 2 : options.M - 3\n dxdy = configuration(:, i) - configuration(:, 1);\n g = [dxdy; dxdy.^2];\n Psi = [Psi; g];\n end;\n % g5\n dxdy = configuration(:, 6) - configuration(:, 2);\n g = [dxdy; dxdy.^2];\n Psi = [Psi; g];\n % g6\n dxdy = configuration(:, 7) - configuration(:, 3);\n g = [dxdy; dxdy.^2];\n Psi = [Psi; g];\n % g7\n dxdy = configuration(:, 8) - configuration(:, 1);\n g = [dxdy; dxdy.^2];\n Psi = [Psi; g];\n \nend\n", "meta": {"author": "uricamic", "repo": "flandmark", "sha": "ecf122f93f73504fe7d8faccca525c6b1e98fdcd", "save_path": "github-repos/MATLAB/uricamic-flandmark", "path": "github-repos/MATLAB/uricamic-flandmark/flandmark-ecf122f93f73504fe7d8faccca525c6b1e98fdcd/learning/code/Functions/buildPsi2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484143, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.39944052246585926}}
{"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 World = doMapping(World, sen, r_new, scan_data, handles)\n\n %%%%%%%%%%%%%%%%%%%%%%%%% MAPPING SETTINGS %%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Amount by which to increment/reduce cell value when obstacle is detected:\n map_augment = 20;\n % Amount by which to reduce cell value when no obstacle is detected:\n map_reduce = 20; \n map_max = 255; % Maximum value that a grid cell can take\n map_min = 0; % Minimum value that a grid cell can take\n map_isOccupied = 150; % Value at which cell is in occupied state\n map_isEmpty = 50; % Value at which cell is in empty state\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n scan_polar = getMeasurement(scan_data);\n % Determine the region in the scan that was detected as being emtpy\n empty_region_pol = ones(2, size(scan_polar, 2) * ...\n (round((sen.range - sen.range_min)/World.map_res) + 1)) * -1;\n position = 1;\n for i = 1:size(scan_polar, 2)\n empty_region_r = sen.range_min : World.map_res : scan_polar(1, i) ...\n - World.map_res;\n empty_region_a = repmat(scan_polar(2, i), 1, length(empty_region_r));\n empty_region_pol(:, position : position + length(empty_region_r) - 1) ...\n = [empty_region_r; empty_region_a];\n position = position + length(empty_region_r);\n end\n empty_region_pol = empty_region_pol(:, empty_region_pol(1, :) ~= -1);\n % Map the empty region of the scan onto the global frame\n empty_region = invScanPoint(r_new, empty_region_pol);\n\n scan_global = transToGlobal(r_new, scan_data);\n gridmap_occupied = zeros(size(World.gridmap));\n gridmap_empty = zeros(size(World.gridmap));\n scan_global = interp1(World.map_vals, World.map_vals, scan_global, 'nearest');\n empty_region = interp1(World.map_vals, World.map_vals, empty_region, 'nearest');\n\n for i = 1:length(World.map_vals)\n for j = 1:length(World.map_vals)\n if ~isempty(scan_global)\n gridmap_occupied(i, j) = sum(scan_global(1,:) == World.map_vals(j) & ...\n scan_global(2,:) == World.map_vals(i));\n end\n gridmap_empty(i, j) = sum(empty_region(1,:) == World.map_vals(j) & ...\n empty_region(2,:) == World.map_vals(i));\n end\n end\n \n World.gridmap_counter = World.gridmap_counter ...\n + map_augment * gridmap_occupied ...\n - map_reduce * gridmap_empty;\n \n % Set the gridmap counter such that the max value is 255 and min value\n % is 0:\n \n World.gridmap_counter(World.gridmap_counter > map_max) = map_max;\n World.gridmap_counter(World.gridmap_counter < map_min) = map_min;\n \n gridmap_occupied = World.gridmap_counter > map_isOccupied;\n gridmap_empty = World.gridmap_counter < map_isEmpty;\n World.gridmap = ones(size(World.gridmap_counter)) * 0.5;\n World.gridmap(gridmap_occupied) = 1;\n World.gridmap(gridmap_empty) = 0;\n \n World.gridmap_greyscale = mat2gray(World.gridmap_counter, [map_min map_max]);\n \n imagesc(flipud(World.gridmap_greyscale), 'parent', handles.map1, [0 1]);\n set(handles.map1, 'XTick', [], 'YTick', []);\n imagesc(flipud(World.gridmap), 'parent', handles.map2, [0 1]);\n set(handles.map2, 'XTick', [], 'YTick', []);\n \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/tools/doMapping.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3993906192635659}}
{"text": "function [xVals, yVals, zVals] = getUniformizedXYZVals(planC)\n%\"getUniformizedXYZVals\"\n% Return the X Y and Z vals of the uniformized dataset.\n%\n% These are arrays, with a value for each row, col and slice in the\n% uniformized dataset.\n%\n% In case of any error accessing the data 0 is returned for all vals.\n%\n% JRA 11/14/03\n%\n% Usage: [xVals, yVals, zVals] = getUniformizedXYZVals(planC)\n\nindexS = planC{end};\n\n[xVals, yVals, junk] = getScanXYZVals(planC{indexS.scan}(1));\n\nscanInfo = planC{indexS.scan}(1).scanInfo(1);\nsizeArray = getUniformizedSize(planC);\n\nuniformScanInfo = planC{indexS.scan}(1).uniformScanInfo;\nnZSlices = sizeArray(3);\nzVals = uniformScanInfo.firstZValue : uniformScanInfo.sliceThickness : uniformScanInfo.sliceThickness * (nZSlices-1) + uniformScanInfo.firstZValue; \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/getUniformizedXYZVals_plnChk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.5851011542032313, "lm_q1q2_score": 0.3993746798334607}}
{"text": "function test_bug2137\n\n% MEM 2gb\n% WALLTIME 00:30:00\n% DEPENDENCY\n\n\n% the following lines are for interactive/manual testing\nif false\n restoredefaultpath\n clear all\n addpath(dccnpath('/home/common/matlab/fieldtrip'));\n ft_defaults\nend\n\ncfg = [];\ncfg.dataset = dccnpath('/home/common/matlab/fieldtrip/data/ftp/test/ctf/Subject01.ds');\ndata = ft_preprocessing(cfg);\n\ncfg = [];\ncfg.detrend = 'no';\ncfg.resamplefs = 150;\ndata = ft_resampledata(cfg, data);\n\ncfg = [];\ncfg.channel = {'MEG'};\ncfg.numcomponent = 60;\ncomp = ft_componentanalysis(cfg, data);\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/test/test_bug2137.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.39937467983346064}}
{"text": "function [N,Vn]=trinorm(F,V)\n\n%% function [N,Vn]=trinorm(F,V)\n% ------------------------------------------------------------------------\n%\n%\n% 2021/09/14 Labelled as depricated\n% ------------------------------------------------------------------------\n\n%%\n\nwarning('The trinorm function is depricated. Use patchNormal instead.'); \n[N,Vn]=patchNormal(F,V);\n\n%% Old\n\n% %N.B. if F does not describe triangles this functions uses first three\n% %vertices as a triangular description\n% \n% \n% %Getting triangle surface normal (cross product of two edge vectors)\n% vec1=[V(F(:,2),1)-V(F(:,1),1) V(F(:,2),2)-V(F(:,1),2) V(F(:,2),3)-V(F(:,1),3)];\n% vec2=[V(F(:,3),1)-V(F(:,1),1) V(F(:,3),2)-V(F(:,1),2) V(F(:,3),3)-V(F(:,1),3)];\n% N=cross(vec1,vec2,2);\n% \n% %Normalizing vector length\n% N=N./(sqrt(sum(N.^2,2))*ones(1,size(N,2)));\n% \n% %Midface coordinates for normal vectors (mean of each face)\n% X=V(:,1); Y=V(:,2); Z=V(:,3);\n% Vn=[mean(X(F),2) mean(Y(F),2) mean(Z(F),2)];\n\nend\n\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/trinorm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105587468141, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.3993716714886666}}
{"text": "function varargout = iff(varargin)\n%IFF Logical equivalence\n%\n% IFF(X,Y) creates a mixed integer representation of\n% the constraint X <--> Y, i.e. Y is true iff X is true.\n%\n% Syntax\n% F = iff(X,Y)\n%\n% Input\n% X : binary SDPVAR variable or a set of linear (in)equalities\n% Y : binary SDPVAR variable or a set of linear (in)equalities\n%\n% Output\n% F : Constraint object\n%\n% Examples\n%\n% binvar X,Y; F = iff(X,Y);\n% sdpvar X;binvar Y; F = iff(X>=5,Y);\n% sdpvar X;binvar Y; F = iff(Y,X==5);\n%\n% Overloading\n%\n% The iff overloads == for logic constraints.\n%\n% sdpvar X;binvar Y; F = ((X>=5) == Y);\n% sdpvar X;binvar Y; F = (Y == (X==5));\n%\n%\n% Note\n% The function IFF is not complete, but will be\n% improved upon in future releases.\n%\n% See also @SDPVAR/AND, @SDPVAR/OR, IMPLIES\n\nX = varargin{1};\nif nargin < 2\n help iff\nend\nY = varargin{2};\n\nswitch class(varargin{1})\n case {'lmi','constraint','sdpvar'}\n varargout{1} = setupMeta(lmi([]), mfilename,varargin{:});\n\n case 'char'\n varargout{1} = iff_internal(varargin{3:end});\nend", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/operators/iff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.39925780874908473}}
{"text": "function cS = plus(cS,v)\n\n% crystal shape should be first argument\nif ~isa(cS,'crystalShape'), [cS,v] = deal(v,cS); end\n\n% shift should be vector3d\nif isa(v,'double') \n if size(v,2)==2, v = [v,ones(size(v,1),1)]; end\n v = vector3d(v.');\nelse\n v = v(:).';\nend\n\n% extent shift by number of vertices of the crystal\nv = repmat(v,size(cS.V,1),1);\n\n% extend the crystals by the number of shifts\nif size(cS.V,2) == 1\n cS = repmat(cS,size(v,2));\nend\n\n% shift vertices\ncS.V = cS.V + v;", "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/@crystalShape/plus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.39925626355850713}}
{"text": "function t=bdt2time(week,sec)\n\nbdt0 =[2006,1, 1,0,0,0]; %beidou time reference\nt0=epoch2time(bdt0);\n\nif sec<-1e9||sec>1e9,sec=0;end\n\nt.time=t0.time+week*7*86400+fix(sec);\nt.sec=sec-fix(sec);\n\nreturn;", "meta": {"author": "kaichen686", "repo": "GINav", "sha": "bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666", "save_path": "github-repos/MATLAB/kaichen686-GINav", "path": "github-repos/MATLAB/kaichen686-GINav/GINav-bc6b3ab6c40db996a4fd8e8ca5b748fe21a23666/src/common/bdt2time.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.39925626355850713}}
{"text": "function [engine, loglik] = enter_evidence(engine, evidence, varargin)\n% ENTER_EVIDENCE Add the specified evidence to the network (hmm)\n% [engine, loglik] = enter_evidence(engine, evidence, ...)\n%\n% evidence{i,t} = [] if if X(i,t) is hidden, and otherwise contains its observed value (scalar or column vector)\n%\n% The following optional arguments can be specified in the form of name/value pairs:\n% [default value in brackets]\n%\n% maximize - if 1, does max-product (not yet supported), else sum-product [0]\n% filter - if 1, does filtering, else smoothing [0]\n% oneslice - 1 means only compute marginals on nodes within a single slice [0]\n%\n% e.g., engine = enter_evidence(engine, ev, 'maximize', 1)\n\nmaximize = 0;\nfilter = 0;\noneslice = 0;\n\n% parse optional params\nargs = varargin;\nnargs = length(args);\nif nargs > 0\n for i=1:2:nargs\n switch args{i},\n case 'maximize', maximize = args{i+1}; \n case 'filter', filter = args{i+1}; \n case 'oneslice', oneslice = args{i+1};\n otherwise, \n error(['invalid argument name ' args{i}]); \n end\n end\nend\n\n[ss T] = size(evidence);\nengine.maximize = maximize;\nengine.evidence = evidence;\nbnet = bnet_from_engine(engine);\nengine.node_sizes = repmat(bnet.node_sizes_slice(:), [1 T]);\n\nobs_bitv = ~isemptycell(evidence(:));\nbitv = reshape(obs_bitv, ss, T);\nfor t=1:T\n onodes = find(bitv(:,t));\n if ~isequal(onodes, bnet.observed(:))\n error(['dbn was created assuming observed nodes per slice were '...\n\t num2str(bnet.observed(:)') ' but the evidence in slice ' num2str(t) ...\n\t ' has observed nodes ' num2str(onodes(:)')]);\n end\nend\n\nobslik = mk_hmm_obs_lik_matrix(engine, evidence);\n\n%[alpha, beta, gamma, loglik, xi] = fwdback(engine.startprob, engine.transprob, obslik, ...\n[alpha, beta, gamma, loglik, xi] = fwdback_twoslice(engine, engine.startprob,...\n engine.transprob, obslik, ...\n 'maximize', maximize, 'fwd_only', filter, ...\n 'compute_xi', ~oneslice);\n\nengine.one_slice_marginal = gamma; % gamma(:,t) for t=1:T\nif ~oneslice\n Q = size(gamma,1);\n engine.two_slice_marginal = reshape(xi, [Q*Q T-1]); % xi(:,t) for t=1:T-1\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/inference/dynamic/@hmm_inf_engine/enter_evidence.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.39925626355850713}}
{"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": "% GAINSANDREFERENCES compute gains matrices, references and other control\n% related quantities for each state of the state machine.\n\n%% --- Initialization ---\n \n% CoM gains\nGain.KP_CoM = [50 100 5 % state == 1 TWO FEET BALANCING\n 50 100 5 % state == 2 COM TRANSITION TO LEFT \n 50 100 5 % state == 3 LEFT FOOT BALANCING\n 50 100 5 % state == 4 YOGA LEFT FOOT \n 50 100 5 % state == 5 PREPARING FOR SWITCHING \n 50 100 5 % state == 6 LOOKING FOR CONTACT\n 50 100 5 % state == 7 TRANSITION TO INITIAL POSITION \n 50 100 5 % state == 8 COM TRANSITION TO RIGHT FOOT\n 50 100 5 % state == 9 RIGHT FOOT BALANCING\n 50 100 5 % state == 10 YOGA RIGHT FOOT \n 50 100 5 % state == 11 PREPARING FOR SWITCHING \n 50 100 5 % state == 12 LOOKING FOR CONTACT\n 50 100 5];% state == 13 TRANSITION TO INITIAL POSITION\n\nGain.KD_CoM = 2*sqrt(Gain.KP_CoM)/20;\n\n% Angular momentum gains\nGain.KI_AngularMomentum = 3;\nGain.KP_AngularMomentum = 2*sqrt(Gain.KI_AngularMomentum)/5;\n\n% Postural task gains\n% % TORSO %% LEFT ARM %% RIGHT ARM %% LEFT LEG %% RIGHT LEG %% \nGain.KP_postural = [10 30 20, 10 10 10 8, 10 10 10 8, 30 30 20 20 100 100, 30 50 30 60 100 100 % state == 1 TWO FEET BALANCING\n 10 30 20, 10 10 10 8, 10 10 10 8, 30 30 20 20 100 100, 30 50 30 60 100 100 % state == 2 COM TRANSITION TO LEFT \n 10 30 20, 10 10 10 8, 10 10 10 8, 30 50 30 60 100 100, 30 30 20 20 100 100 % state == 3 LEFT FOOT BALANCING\n 30 30 30, 10 10 10 10, 10 10 10 10,100 200 100 400 100 100,100 50 30 100 100 100 % state == 4 YOGA LEFT FOOT \n 30 30 30, 5 5 10 10, 10 10 20 10,200 250 20 20 10 10,220 550 220 200 65 300 % state == 5 PREPARING FOR SWITCHING \n 30 30 30, 10 10 20 10, 10 10 20 10,100 350 20 200 10 100,220 550 220 200 65 300 % state == 6 LOOKING FOR CONTACT\n 30 30 30, 10 10 10 8, 10 10 10 8, 30 50 60 30 5 5, 30 30 30 20 5 5 % state == 7 TRANSITION TO INITIAL POSITION \n 10 30 20, 10 10 10 8, 10 10 10 8, 30 50 60 30 100 100, 30 30 30 20 100 100 % state == 8 COM TRANSITION TO RIGHT FOOT\n 10 30 20, 10 10 10 8, 10 10 10 8, 30 50 30 60 100 100, 30 30 20 20 100 100 % state == 9 RIGHT FOOT BALANCING\n 30 30 30, 10 10 10 10, 10 10 10 10,100 50 30 100 100 100,100 200 100 100 10 10 % state == 10 YOGA RIGHT FOOT \n 30 30 30, 10 10 10 10, 10 10 10 10,220 550 220 200 65 300,200 250 20 20 10 10 % state == 11 PREPARING FOR SWITCHING \n 30 30 30, 10 10 10 10, 10 10 10 10,220 550 220 200 65 300,100 350 20 200 10 100 % state == 12 LOOKING FOR CONTACT\n 30 30 30, 10 10 10 10, 10 10 10 10,220 550 220 200 65 300,100 350 20 200 10 100];% state == 13 TRANSITION TO INITIAL POSITION\n\nGain.KD_postural = 2*sqrt(Gain.KP_postural(1,:))/20; \n\n% symmetric gains\nGain.KP_postural(10,18:23) = Gain.KP_postural(10,18:23)*1.5; \nGain.KP_postural(10,1:3) = Gain.KP_postural(10,1:3)*2;\nGain.KP_postural(4,12:17) = Gain.KP_postural(4,12:17)*1.5; \nGain.KP_postural(4,1:3) = Gain.KP_postural(4,1:3)*2;\nGain.KP_postural(4,4:11) = Gain.KP_postural(4,4:11)*1.5;\nGain.KP_postural(7,2:3) = Gain.KP_postural(7,2:3)*1.5;\n\n%% Smoothing times\n\n% Smoothing time gain scheduling\nConfig.SmoothingTimeGainScheduling = 2;\n\n% Smoothing time CoM references\nStateMachine.CoMSmoothingTime = [1; %% state == 1 TWO FEET BALANCING\n 1; %% state == 2 COM TRANSITION TO LEFT FOOT\n 1; %% state == 3 LEFT FOOT BALANCING \n 0.65; %% state == 4 YOGA LEFT FOOT\n 2; %% state == 5 PREPARING FOR SWITCHING\n 2; %% state == 6 LOOKING FOR CONTACT \n 1; %% state == 7 TRANSITION INIT POSITION\n 1; %% state == 8 COM TRANSITION TO RIGHT FOOT\n 1; %% state == 9 RIGHT FOOT BALANCING \n 0.65; %% state == 10 YOGA RIGHT FOOT\n 2; %% state == 11 PREPARING FOR SWITCHING\n 5; %% state == 12 LOOKING FOR CONTACT \n 10]; %% state == 13 TRANSITION INIT POSITION\n\n% Smoothing time for joints references \nStateMachine.jointsSmoothingTime = [1; %% state == 1 TWO FEET BALANCING\n 1; %% state == 2 COM TRANSITION TO LEFT FOOT\n 1; %% state == 3 LEFT FOOT BALANCING \n 0.65; %% state == 4 YOGA LEFT FOOT\n 2; %% state == 5 PREPARING FOR SWITCHING\n 2; %% state == 6 LOOKING FOR CONTACT \n 1; %% state == 7 TRANSITION INIT POSITION\n 1; %% state == 8 COM TRANSITION TO RIGHT FOOT\n 1; %% state == 9 RIGHT FOOT BALANCING \n 0.65; %% state == 10 YOGA RIGHT FOOT\n 2; %% state == 11 PREPARING FOR SWITCHING\n 5; %% state == 12 LOOKING FOR CONTACT \n 10]; %% state == 13 TRANSITION INIT POSITION\n\n% scale factor smoothing time multiplies the smoothing factor during the\n% Yoga (state 4 and 10). The purpose is to reduce the time necessary for \n% the reference to converge to the next position, but without changing also\n% the valuse stored in Sm.joints_leftYogaRef/Sm.joints_rightYogaRef\nStateMachine.scaleFactorSmoothingTime = 0.9;\n \n%% CoM delta\n\n% To be summed to the reference CoM position\nStateMachine.CoM_delta = [% THIS REFERENCE IS USED AS A DELTA W.R.T. THE POSITION OF THE LEFT FOOT\n 0.0, 0.00, 0.0; %% NOT USED\n 0.0, 0.00, 0.0; %% state == 2 COM TRANSITION TO LEFT FOOT\n 0.0, 0.005, 0.0; %% state == 3 LEFT FOOT BALANCING \n 0.0, 0.005, 0.0; %% state == 4 YOGA LEFT FOOT\n 0.0, 0.00, 0.0; %% state == 5 PREPARING FOR SWITCHING\n 0.02, -0.08, 0.0; %% state == 6 LOOKING FOR CONTACT \n 0.0, 0.00, 0.0; %% state == 7 TWO FEET BALANCING\n % THIS REFERENCE IS USED AS A DELTA W.R.T. THE POSITION OF THE RIGHT FOOT\n 0.0, 0.00, 0.0; %% state == 8 COM TRANSITION TO RIGHT FOOT\n 0.0, 0.00, 0.0; %% state == 9 RIGHT FOOT BALANCING \n 0.0, -0.01, 0.0; %% state == 10 YOGA RIGHT FOOT\n 0.0, 0.00, 0.0; %% state == 11 PREPARING FOR SWITCHING\n 0.0, 0.09, 0.0; %% state == 12 LOOKING FOR CONTACT \n 0.0, 0.00, 0.0]; %% NOT USED\n\n%% Joint references\nStateMachine.joints_references = [ zeros(1,ROBOT_DOF); %% THIS REFERENCE IS IGNORED \n [-0.0348,0.0779,0.0429, ... %% state == 2 COM TRANSITION TO LEFT \n -0.1493,0.8580,0.2437,0.8710, ... %\n -0.1493,0.8580,0.2437,0.8710, ... %\n -0.0015,-0.1109,-0.0001,0.0003,0.0160,0.1630, ... % \n 0.0005,0.0793,-0.0014,-0.0051,0.0073,-0.1151]; % \n [ 0.0864,0.0258,0.0152, ... %% state == 3 LEFT FOOT BALANCING\n 0.1253,0.8135,0.3051,0.7928, ... % \n 0.0563,0.6789,0.3340,0.6214, ... %\n -0.0015,-0.1109,-0.0001,0.0003,0.0160,0.1630, ... % \n 0.0005,0.0793,-0.0014,-0.0051,-0.1060,-0.1151]; % \n zeros(1,ROBOT_DOF); %% THIS REFERENCE IS IGNORED \n [-0.0348,0.0779,0.0429, ... %% state == 5 PREPARING FOR SWITCHING\n -0.1493,0.8580,0.2437,0.8710, ... %\n -0.1493,0.8580,0.2437,0.8710, ... %\n -0.0015,-0.1109,-0.0001,0.0003,0.0160,0.1630, ... % \n 0.0005,0.0793,-0.0014,-0.0051,0.0073,-0.1151]; % \n [ 0.0864,0.0258,0.0152, ... %% state == 6 LOOKING FOR CONTACT\n 0.1253,0.8135,0.3051,0.7928, ... %\n 0.0563,0.6789,0.3340,0.6214, ... %\n 0.0107,-0.0741,-0.0001,-0.0120,0.0252,0.1369, ... %\n -0.0026,0.0225,0.0093,-0.0020,0.0027,-0.0277]; % \n zeros(1,ROBOT_DOF); %% THIS REFERENCE IS IGNORED\n [ 0.0864,0.0258,0.0152, ... %% state == 8 COM TRANSITION TO RIGHT FOOT\n 0.1253,0.8135,0.3051,0.7928, ... %\n 0.0563,0.6789,0.3340,0.6214, ... %\n 0.0107,-0.0741,-0.0001,-0.0120,0.0252,0.1369, ... %\n -0.0026,0.0225,0.0093,-0.0020,0.0027,-0.0277]; % \n [ 0.0864,0.0258,0.0152, ... %% state == 9 RIGHT FOOT BALANCING\n 0.1253,0.8135,0.3051,0.7928, ... % \n 0.0563,0.6789,0.3340,0.6214, ... %\n 0.0005,0.0793,-0.0014,-0.0051,0.0073,-0.1151, ... % \n -0.0015,-0.1109,-0.0001,0.0003,0.0160,0.1630]; % \n zeros(1,ROBOT_DOF); %% THIS REFERENCE IS IGNORED \n [-0.0348,0.0779,0.0429, ... %% state == 11 PREPARING FOR SWITCHING\n -0.1493,0.8580,0.2437,0.8710, ... %\n -0.1493,0.8580,0.2437,0.8710, ... %\n 0.0005,0.0793,-0.0014,-0.0051,0.0073,-0.1151, ... % \n -0.0015,-0.1109,-0.0001,0.0003,0.0160,0.1630]; % \n [ 0.0864,0.0258,0.0152, ... %% state == 12 LOOKING FOR CONTACT\n 0.1253,0.8135,0.3051,0.7928, ... %\n 0.0563,0.6789,0.3340,0.6214, ... %\n -0.0026,0.0225,0.0093,-0.0020,0.0027,-0.0277, ... %\n 0.0107,-0.0741,-0.0001,-0.0120,0.0252,0.1369]; % \n zeros(1,ROBOT_DOF)]; %% THIS REFERENCE IS IGNORED \n \n\n% YOGA MOVESET (joint references during state 4 and 10)\nq1 = [-0.0790,0.2279, 0.4519, ...\n -1.1621,0.6663, 0.4919, 0.9947, ... \n -1.0717,1.2904,-0.2447, 1.0948, ...\n 0.2092,0.2060, 0.0006,-0.1741,-0.1044, 0.0700, ...\n 0.3484,0.4008,-0.0004,-0.3672,-0.1060,-0.0875];\n\nq2 = [-0.0790,0.1279, 0.4519, ...\n -1.1621,0.6663, 0.4965, 0.9947, ...\n -1.0717,1.2904,-0.2493, 1.0948, ...\n 0.2092,0.2060, 0.0006,-0.1741,-0.1044,0.0700, ... \n 0.3714,0.9599, 1.3253,-1.6594,-0.1060,-0.0614];\n \nq3 = [-0.0852,-0.3273,0.0821,...\n 0.1391, 1.4585,0.2464, 0.3042, ...\n -0.4181, 1.6800,0.7373, 0.3031, ...\n 0.2092,0.2060, 0.0006,-0.1741,-0.1044,0.0700, ...\n 0.3714,0.9599, 1.3253,-1.6594, 0.2443,-0.0614];\n \nq4 = [-0.0852,-0.4273,0.0821,...\n 0.1391, 1.4585,0.2464, 0.3042, ...\n -0.4181, 1.6800,0.7373, 0.3031, ...\n 0.2092, 0.3473,0.0006,-0.1741,-0.1044, 0.0700, ...\n 0.3514, 1.3107,1.3253,-0.0189, 0.2443,-0.0614];\n \nq5 = [-0.0790,-0.2273, 0.4519, ...\n -1.1621,0.6663, 0.4965, 0.9947, ...\n -1.0717,1.2904,-0.2493, 1.0948, ...\n 0.2092, 0.4473,0.0006,-0.1741,-0.1044, 0.0700, ...\n 0.3514, 1.3107,1.3253,-0.0189, 0.2443,-0.0614];\n \nq6 = [-0.0852,-0.4273,0.0821, ...\n 0.1391, 1.4585,0.2464, 0.3042, ...\n -0.4181, 1.6800,0.7373, 0.3031, ...\n 0.2092, 0.6473,0.0006,-0.1741,-0.1044, 0.0700, ...\n 0.3514, 1.3107,1.3253,-0.0189, 0.2443,-0.0614];\n \nq7 = [-0.0852,-0.4273,0.0821, ...\n 0.1391, 1.4585,0.2464, 0.3042, ...\n -0.4181, 1.6800,0.7373, 0.3031, ...\n 0.2092, 0.6473,0.0006,-0.1741,-0.1044, 0.0700, ...\n 0.3514, 1.3107,1.3253, -1.6217, 0.2443,-0.0614];\n \nq8 = [-0.0852,-0.4273,0.0821, ...\n 0.1391, 1.4585,0.2464, 0.3042, ...\n -0.4181, 1.6800,0.7373, 0.3031, ...\n 0.2092, 0.6473,0.0006,-0.1741,-0.1044, 0.0700, ...\n 0.3514, 1.3107,1.3253,-0.0189, 0.2443,-0.0614];\n \nq9 = [-0.0852,-0.4273,0.0821, ...\n 0.1391, 1.4585,0.2464, 0.3042, ...\n -0.4181, 1.6800,0.7373, 0.3031, ...\n 0.2092, 0.6473,0.0006,-0.1741,-0.1044, 0.0700, ...\n 0.3514, 0.0107,1.3253,-0.0189, 0.2443,-0.0614];\n \nq10 = [-0.0852,-0.4273,0.0821, ...\n 0.1391, 1.4585,0.2464, 0.3042, ...\n -0.4181, 1.6800,0.7373, 0.3031, ...\n 0.2092, 0.6473,0.0006,-0.1741,-0.1044, 0.0700, ...\n 0.3514, 1.3107,1.3253,-0.0189, 0.2443,-0.0614];\n \nq11 = [-0.0852,-0.4273,0.0821, ...\n 0.1391, 1.4585,0.2464, 0.3042, ...\n -0.4181, 1.6800,0.7373, 0.3031, ...\n 0.2092, 0.6473,0.0006,-0.1741,-0.1044, 0.0700, ...\n 0.8514, 1.3107,1.3253,-0.0189, 0.2443,-0.0614];\n\nq12 = [-0.0852,-0.4273,0.0821, ...\n 0.1391, 1.4585,0.2464, 0.3042, ...\n -0.4181, 1.6800,0.7373, 0.3031, ...\n 0.2092, 0.6473,0.0006,-0.1741,-0.1044, 0.0700, ...\n 0.8514, 0.3107,1.3253,-0.0189, 0.2443,-0.0614];\n \nq13 = [-0.0852,-0.4273,0.0821, ...\n 0.1391, 1.4585,0.2464, 0.3042, ...\n -0.4181, 1.6800,0.7373, 0.3031, ...\n 0.2092, 0.6473,0.0006,-0.1741,-0.1044, 0.0700, ...\n 0.8514, 1.3107,1.3253,-0.0189, 0.2443,-0.0614];\n \nq14 = [-0.0852,-0.4273,0.0821, ...\n 0.1391, 1.4585,0.2464, 0.3042, ...\n -0.4181, 1.6800,0.7373, 0.3031, ...\n 0.2092, 0.6473,0.0006,-0.1741,-0.1044, 0.0700, ...\n 0.8514, 0.0107,1.3253,-0.0189, 0.2443,-0.0614];\n \nq15 = [-0.0852,-0.4273,0.0821, ...\n 0.1391, 1.4585,0.2464, 0.3042, ...\n -0.4181, 1.6800,0.7373, 0.3031, ...\n 0.2092, 0.6473,0.0006,-0.1741,-0.1044, 0.0700, ...\n 1.5514, 0.3107,1.3253,-0.0189, 0.2443,-0.0614];\n \nq16 = [-0.0852,-0.4273,0.0821, ...\n 0.1391, 1.4585,0.2464, 0.3042, ...\n -0.4181, 1.6800,0.7373, 0.3031, ...\n 0.2092, 0.6473,0.0006,-0.1741,-0.1044, 0.0700, ...\n 0.2514, 0.0107,1.3253,-0.0189, 0.2443,-0.0614];\n \nq17 = [-0.0852,-0.4273,0.0821, ...\n 0.1391, 1.4585,0.2464, 0.3042, ...\n -0.4181, 1.6800,0.7373, 0.3031, ...\n 0.2092, 0.6473,0.0006,-0.1741,-0.1044, 0.0700, ...\n -0.3514, 0.3107,1.3253,-0.0189, 0.2443,-0.0614];\n \nStateMachine.joints_leftYogaRef = [ 0, q1;\n 1*StateMachine.jointsSmoothingTime(4),q2;\n 2*StateMachine.jointsSmoothingTime(4),q3;\n 3*StateMachine.jointsSmoothingTime(4),q4;\n 4*StateMachine.jointsSmoothingTime(4),q5;\n 5*StateMachine.jointsSmoothingTime(4),q6;\n 6*StateMachine.jointsSmoothingTime(4),q7;\n 7*StateMachine.jointsSmoothingTime(4),q8;\n 8*StateMachine.jointsSmoothingTime(4),q9;\n 9*StateMachine.jointsSmoothingTime(4),q10;\n 10*StateMachine.jointsSmoothingTime(4),q11;\n 11*StateMachine.jointsSmoothingTime(4),q12;\n 12*StateMachine.jointsSmoothingTime(4),q13;\n 13*StateMachine.jointsSmoothingTime(4),q14;\n 14*StateMachine.jointsSmoothingTime(4),q15;\n 15*StateMachine.jointsSmoothingTime(4),q16;\n 16*StateMachine.jointsSmoothingTime(4),q17;\n 17*StateMachine.jointsSmoothingTime(4),q10;\n 18*StateMachine.jointsSmoothingTime(4),q11;\n 19*StateMachine.jointsSmoothingTime(4),q12;\n 20*StateMachine.jointsSmoothingTime(4),q13;\n 21*StateMachine.jointsSmoothingTime(4),q14;\n 22*StateMachine.jointsSmoothingTime(4),q15;\n 23*StateMachine.jointsSmoothingTime(4),q16;\n 24*StateMachine.jointsSmoothingTime(4),q17;\n 25*StateMachine.jointsSmoothingTime(4),q8];\n \nStateMachine.joints_rightYogaRef = StateMachine.joints_leftYogaRef;\nStateMachine.joints_rightYogaRef(:,1) = [0;\n 1*StateMachine.jointsSmoothingTime(10);\n 2*StateMachine.jointsSmoothingTime(10);\n 3*StateMachine.jointsSmoothingTime(10);\n 4*StateMachine.jointsSmoothingTime(10);\n 5*StateMachine.jointsSmoothingTime(10);\n 6*StateMachine.jointsSmoothingTime(10);\n 7*StateMachine.jointsSmoothingTime(10);\n 8*StateMachine.jointsSmoothingTime(10);\n 9*StateMachine.jointsSmoothingTime(10);\n 10*StateMachine.jointsSmoothingTime(10);\n 11*StateMachine.jointsSmoothingTime(10);\n 12*StateMachine.jointsSmoothingTime(10);\n 13*StateMachine.jointsSmoothingTime(10);\n 14*StateMachine.jointsSmoothingTime(10);\n 15*StateMachine.jointsSmoothingTime(10);\n 16*StateMachine.jointsSmoothingTime(10);\n 17*StateMachine.jointsSmoothingTime(10);\n 18*StateMachine.jointsSmoothingTime(10);\n 19*StateMachine.jointsSmoothingTime(10);\n 20*StateMachine.jointsSmoothingTime(10);\n 21*StateMachine.jointsSmoothingTime(10);\n 22*StateMachine.jointsSmoothingTime(10);\n 23*StateMachine.jointsSmoothingTime(10);\n 24*StateMachine.jointsSmoothingTime(10);\n 25*StateMachine.jointsSmoothingTime(10)];\n\n% if the demo is not \"yogaExtended\", stop at the 8th move\nif ~StateMachine.yogaExtended\n \n StateMachine.joints_leftYogaRef = StateMachine.joints_leftYogaRef(1:8,:);\n StateMachine.joints_rightYogaRef = StateMachine.joints_rightYogaRef(1:8,:);\n StateMachine.joints_leftYogaRef(8,1) = 15*StateMachine.jointsSmoothingTime(4);\n StateMachine.joints_rightYogaRef(8,1) = 15*StateMachine.jointsSmoothingTime(10);\nend\n\n% MIRROR YOGA LEFT MOVESET FOR RIGHT YOGA\t\t\t\t\t \nfor i = 1:size(StateMachine.joints_rightYogaRef,1)\t\n \n\tStateMachine.joints_rightYogaRef(i,2:4) = [StateMachine.joints_rightYogaRef(i,2) -StateMachine.joints_rightYogaRef(i,3) -StateMachine.joints_rightYogaRef(i,4)];\n\trightArm = StateMachine.joints_rightYogaRef(i,end-15:end-12);\n\tStateMachine.joints_rightYogaRef(i,end-15:end-12) = StateMachine.joints_rightYogaRef(i,end-19:end-16);\n\tStateMachine.joints_rightYogaRef(i,end-19:end-16) = rightArm;\n\trightLeg = StateMachine.joints_rightYogaRef(i,end-5:end);\n\tStateMachine.joints_rightYogaRef(i,end-5:end) = StateMachine.joints_rightYogaRef(i,end-11:end-6);\n\tStateMachine.joints_rightYogaRef(i,end-11:end-6) = rightLeg;\nend\t \n\n%% References for CoM trajectory (COORDINATOR DEMO ONLY)\n\n% that the robot waits before starting the left-and-right \nConfig.noOscillationTime = 0; \nConfig.directionOfOscillation = [0;1;0];\nConfig.amplitudeOfOscillation = 0.02; % [m] \nConfig.frequencyOfOscillation = 0.2; % [Hz]", "meta": {"author": "robotology", "repo": "whole-body-controllers", "sha": "90ff965a523f0a120e6a8981b71326c1485e7742", "save_path": "github-repos/MATLAB/robotology-whole-body-controllers", "path": "github-repos/MATLAB/robotology-whole-body-controllers/whole-body-controllers-90ff965a523f0a120e6a8981b71326c1485e7742/controllers/floating-base-balancing-torque-control/app/robots/iCubGenova02/gainsAndReferences.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.3992080411430459}}
{"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": "function [Fconv,no_changed,infeasible,Forigquad] = convertquadratics(F)\n%CONVERTQUADRATICS Internal function to extract quadratic constraints\n\n% ******************************\n% LINEAR?\n% ******************************\n\ninfeasible = 0;\nFconv = F;\nno_changed = 0;\nForigquad = [];\n\nif islinear(F)\n return\nend\n\n[monomtable,variabletype] = yalmip('monomtable');\n\nif any(variabletype == 4)\n if issigmonial(F)\n return\n end\nend\n\nFconv = lmi;\nno_changed = 0;\ni_changed = [];\n% Make sure bounds a pre-processed, in case we look for rotated cone which\n% requires us to know lower bounds\nnv = yalmip('nvars');\nLU = yalmip('getbounds',1:nv);\nLUhere = getbounds(F,[],LU);\nfor i = 1:1:length(F)\n if max(variabletype(getvariables(F(i)))) <= 1\n % Definitely no quadratic to model as all variables are bilinear at\n % most\n Fconv = Fconv + F(i);\n elseif is(F(i),'element-wise') & ~is(F(i),'linear') & ~is(F(i),'sigmonial')\n % f-c'*x-x'*Q*x>0\n fi = sdpvar(F(i));fi = fi(:);\n %[Qs,cs,fs,x,info] = vecquaddecomp(fi);\n for j = 1:length(fi)\n fij = fi(j);\n if isa(fij,'double')\n if fij < 0\n infeasible = 1; \n warning('The problem is trivially infeasible. You have a term POSITIVE NUMBER < 0.');\n return\n end\n end\n % Q = Qs{j};c = cs{j};f = fs{j};\n if max(variabletype(getvariables(fij))) <= 1\n % There are at most bilinear terms, so it cannot be convex\n info = 1;\n else\n [Q,c,f,x,info] = quaddecomp(fij);\n end\n if info==0\n if nnz(Q)==0\n % Oh, linear,...\n Fconv = Fconv + (fi(j)>=0);\n else\n % Yes, quadratic, but convex?\n % Change sign definitions\n Q = -Q;\n c = -c;\n f = -f;\n % Semi-definite case when only part of x in Q\n % Occurs, e.g, in constraints like y'*Q*y < t\n used = find(any(Q));Qred=Q(:,used);Qred = Qred(used,:);xred = x(used);\n [R,p]=chol(Qred);\n done = 0;\n if p\n % Safety check to account for low rank problems\n if all(eig(full(Qred))>=-1e-12)\n [u,s,v]=svd(full(Qred));\n r=find(diag(s)>1e-12);\n R=(u(:,r)*sqrt(s(r,r)))';\n p=0;\n else\n % Try to detect rotated SOCP (x-d)'*A*(x-d)+k<= C*y*z\n yzCandidates = find(~diag(Qred));\n if length(yzCandidates) == 2 && nnz(c(yzCandidates))==0\n %LU = yalmip('getbounds',getvariables(xred(yzCandidates)));\n LU = LUhere(getvariables(xred(yzCandidates)),:);\n if all(LU(:,1)>=0)\n yzSubQ = Qred(yzCandidates,yzCandidates);\n if yzSubQ(1,2) < 0\n C = -2*yzSubQ(1,2);\n xCandidates = setdiff(1:length(used),yzCandidates);\n A = Qred(xCandidates,xCandidates);\n [B,p]=chol(A);\n if ~p\n y = xred(yzCandidates(1));\n z = xred(yzCandidates(2));\n d = -A\\(c(xCandidates)/2);\n k = f-d'*A*d;\n if abs(k)<= 1e-12\n Fconv=Fconv + lmi(rcone(B*(xred(xCandidates)-d),.5*C*y,z));\n no_changed = no_changed + 1;\n i_changed = [i_changed i];\n done = 1;\n elseif k >= -1e-12\n Fconv=Fconv + lmi(rcone([B*(xred(xCandidates)-d);sqrt(abs(k))],.5*C*y,z));\n no_changed = no_changed + 1;\n i_changed = [i_changed i];\n done = 1;\n else\n p = 1;\n end\n end\n end\n end\n end\n end\n end\n if p==0 && ~done\n % Write as second order cone\n d = -c'*x-f;\n if isa(d,'double')\n if d<0\n infeasible = 1;\n return\n else\n Fconv=Fconv + lmi(cone([R*xred],sqrt(d)));\n end\n else\n if length(c) == length(xred)\n ctilde = -(R')\\(c/2); \n Fconv=Fconv + lmi(cone([R*xred;.5*(1-d)],.5*(1+d))); \n else\n Fconv=Fconv + lmi(cone([R*xred;.5*(1-d)],.5*(1+d)));\n end\n end\n no_changed = no_changed + 1;\n i_changed = [i_changed i]; \n elseif ~done\n Fconv = Fconv + lmi(fi(j));\n end\n end\n else\n Fconv = Fconv + lmi(fi(j));\n end\n end\n else\n Fconv = Fconv + F(i);\n end\nend\nif ~isempty(i_changed)\n Forigquad = F(i_changed);\nelse\n Fconv = F;\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/convertquadratics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.39913531337734715}}
{"text": "function [vITRS,rotMat]=TIRS2ITRS(vTIRS,TT1,TT2,xpyp)\n%%TIRS2ITRS Rotate vectors from the Terrestrial Intermediate Reference\n% System (TIRS) to the International Terrestrial Reference\n% System (ITRS). The ITRS is essentially the WGS-84 coordinate\n% system: it defines locations with respect to the crust of a\n% non-rotating Earth, where the z axis passes through a fixed\n% point on the surface. On the other hand, the TIRS is nearly\n% the same except the z axis is the axis of rotation of the\n% Earth, which slowly varies over time. Note that the velocity\n% conversion does not include the (small) centrifugal effect of\n% polar motion.\n%\n%INPUTS: x The NXnumVec collection of vectors in TIRS coordinates to\n% convert (units do not matter). N can be 3, or 6. If the vectors\n% are 3D, then they are position. 6D\n% vectors are assumed to be position and velocity. Since the TIRS\n% and ITRS co-rotate, there is no Coriolis effect to add. Also,\n% the accelerations due to the wobble of the rotation axis over\n% time are not considered. These accelerations are very small.\n% Thus, the function just rotates both halves of the vector.\n% TT1, TT2 Two parts of a Julian date given in terrestrial time (TT).\n% The units of the date are days. The full date is the sum of\n% both terms. The date is broken into two parts to provide\n% more bits of precision. It does not matter how the date is\n% split.\n% xpyp xpyp=[xp;yp] are the polar motion coordinates in radians\n% including the effects of tides and librations. If this\n% parameter is omitted or if an empty matrix is passed, the\n% value from the function getEOP will be used.\n%\n%OUTPUTS: vITRS The NXnumVec vector of values of x rotated from the TIRS\n% into the ITRS.\n% rotMat The 3X3 rotation matrix used to rotate vectors from the\n% TIRS into the ITRS.\n%\n%The conversion functions from the International Astronomical Union's\n%(IAU) Standard's of Fundamental Astronomy library are put together to get\n%the necessary rotation matrix.\n%\n%The algorithm can be compiled for use in Matlab using the \n%CompileCLibraries function.\n%\n%The algorithm is run in Matlab using the command format\n%[vITRS,rotMat]=TIRS2ITRS(vTIRS,TT1,TT2)\n%or if more parameters are known, using the format\n%[vITRS,rotMat]=TIRS2ITRS(vTIRS,TT2,TT2,xpyp);\n%\n%Different celestial coordinate systems 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,\n% Naval Research Laboratory, no. NRL/FR/5344--16-10,279, 10 Aug. 2016,\n% 173 pages.\n%\n%March 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nerror('This function is only implemented as a mexed C or C++ function. Please run CompileCLibraries.m to compile the function for use.')\n\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/Coordinate_Systems/Celestial_and_Terrestrial_Systems/TIRS2ITRS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3991189131205236}}
{"text": "function drawplat3d(nodez,lc,lm)\nimport rvctools.*\nhold on\nnodenum = size(nodez,1);\nfor j=1:nodenum\n if size(nodez,2)==12\n xc = [nodez(j,1:2),nodez(j,12),0,0,nodez(j,3)];\n xr = [nodez(j,1:2),0,0,0,nodez(j,3)]; a = nodez(j,4:7); th = nodez(j,8:11);\n else\n xc = [nodez(j,1:2),nodez(j,4),0,0,0];\n xr = [nodez(j,1:2),0,0,0,0]; a = nodez(j,3)*ones(1,4); th = zeros(1,4);\n end\n cub = pkgMechanics.RigidCuboid(1,xc,lc);\n patch('Vertices',cub.verticesStates.position','Faces',cub.faces,'FaceColor','b','FaceAlpha',0.5);\n \n xm = xr2m(xr,a,th,lc,lm);\n % build mobile platform cuboid\n for i=1:4\n plat(i) = pkgMechanics.RigidCuboid(1,xm(i,:),lm);\n patch('Vertices',plat(i).verticesStates.position','Faces',plat(i).faces,'FaceColor','y','FaceAlpha',0.5);\n end\nend\nhold off\nend", "meta": {"author": "star2dust", "repo": "paper-simulation", "sha": "2d35e3beeccd2ce41f60c59e347b090f25960706", "save_path": "github-repos/MATLAB/star2dust-paper-simulation", "path": "github-repos/MATLAB/star2dust-paper-simulation/paper-simulation-2d35e3beeccd2ce41f60c59e347b090f25960706/Alonso2017Multi/drawplat3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.5, "lm_q1q2_score": 0.39909339367050706}}
{"text": "function v = axis(q,varargin)\n% rotational axis of the quaternion\n%\n% Syntax\n% v = axis(q)\n%\n% Input\n% q - @quaternion\n%\n% Output\n% v - @vector3d\n\nv = vector3d(q.b,q.c,q.d);\nv(q.a<0) = -v(q.a<0);\nv(isnull(norm(v))) = xvector;\nv = v./norm(v);\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/geometry/@quaternion/axis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.39894235816738255}}
{"text": "function [x] = boundProject(x,LB,UB)\n% function [x] = boundProject(x,LB,UB)\n% Computes projection of x onto constraints LB <= x <= UB\n\nx(x < LB) = LB(x < LB);\nif nargin > 2\nx(x > UB) = UB(x > UB);\nend", "meta": {"author": "rbgirshick", "repo": "voc-dpm", "sha": "c0b88564bd668bcc6216bbffe96cb061613be768", "save_path": "github-repos/MATLAB/rbgirshick-voc-dpm", "path": "github-repos/MATLAB/rbgirshick-voc-dpm/voc-dpm-c0b88564bd668bcc6216bbffe96cb061613be768/external/minConf/minConf/boundProject.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.39894235816738255}}
{"text": "function c = sum(a,dim)\n%SUM Implements sum(a,dim) for slopes\n%\n% u = sum(a,dim)\n%\n%parameter dim optional, functionality as Matlab function sum\n%\n\n% written 12/06/98 S.M. Rump\n% modified 09/28/01 S.M. Rump matrices and multi-dimensional arrays\n% modified 04/04/04 S.M. Rump set round to nearest for safety\n% modified 04/06/05 S.M. Rump rounding unchanged\n% modified 09/28/08 S.M. Rump check for rounding to nearest improved\n%\n\n e = 1e-30;\n if 1+e==1-e % fast check for rounding to nearest\n rndold = 0;\n else\n rndold = getround;\n setround(0)\n end\n\n if nargin==1\n if a.size(1)==1\n dim = 2;\n else\n dim = 1;\n end\n end\n\n if dim==1\n c = ones(1,a.size(1))*a;\n else\n c = a*ones(a.size(2),1);\n end\n \n setround(rndold)\n", "meta": {"author": "douthwja01", "repo": "OpenMAS", "sha": "962f321f82167db78066b2c88c783423ecc3b73a", "save_path": "github-repos/MATLAB/douthwja01-OpenMAS", "path": "github-repos/MATLAB/douthwja01-OpenMAS/OpenMAS-962f321f82167db78066b2c88c783423ecc3b73a/toolboxes/Intlab_V7.1/slope/@slope/sum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710085, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.3989423581673825}}
{"text": "function N = count_network_parameters(net)\n% -------------------------------------------------------------------------\n% Description:\n% Count the total number of network parameters\n%\n% Input:\n% - net : network\n%\n% Output:\n% - N : #parameters\n%\n% Citation: \n% Fast and Accurate Image Super-Resolution with Deep Laplacian Pyramid Networks\n% Wei-Sheng Lai, Jia-Bin Huang, Narendra Ahuja, and Ming-Hsuan Yang\n% arXiv, 2017\n%\n% Contact:\n% Wei-Sheng Lai\n% wlai24@ucmerced.edu\n% University of California, Merced\n% -------------------------------------------------------------------------\n\n N = 0;\n for i = 1:length(net.params)\n\n N = N + numel(net.params(i).value);\n\n end\n\n\nend", "meta": {"author": "phoenix104104", "repo": "LapSRN", "sha": "95154bba82a3aab9bdaec8e0eedd4187babc5ed2", "save_path": "github-repos/MATLAB/phoenix104104-LapSRN", "path": "github-repos/MATLAB/phoenix104104-LapSRN/LapSRN-95154bba82a3aab9bdaec8e0eedd4187babc5ed2/utils/count_network_parameters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.39894235423056446}}
{"text": "%%%%%%%%%%Programmed by: Chi-Hang Kwan%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%Completion Date: December 13, 2012%%%%%%%%%%%%%%%%%%%\n\nfunction posc_new = AI(window,pos,vel,posc,tstep)\ntb = get(window,'UserData');\n\nposf = pos + vel*tstep; %the position of the puck at the next frame\nmaxspeed = 1; %maximum moving speed of the computer's mallet\n\nif posf(2) < 0\n pos_desire = [posf(1) tb.fieldh/4];\nelse\n if (posc(2)-posf(2)) > tb.r_mallet && abs(posf(1)-posc(1)) < tb.r_mallet %sweet spot to strike\n pos_desire = posf;\n if (posc(2)-posf(2))<(tb.r_mallet + tb.r_puck + 0.06) \n maxspeed = 2; %accelerate to hit puck when it is within 6cm of impact\n end\n else\n pos_desire(2) = posf(2) + tb.r_mallet+tb.r_puck + 0.03;\n if (posf(2)-posc(2))>=(tb.r_mallet-tb.r_puck)\n pos_desire(1) = posf(1) + sign(posc(1)-posf(1))*(tb.r_mallet+tb.r_puck+0.01);\n else\n pos_desire(1) = posf(1);\n end\n end\nend\n\n%%%%%%%%%%To ensure the mallet stays within its own half%%%%%%%%%%%%%\nif abs(pos_desire(1))>tb.fieldw/2-tb.r_mallet \n pos_desire(1)= sign(pos_desire(1))*(tb.fieldw/2-tb.r_mallet);\nend\nif pos_desire(2) > tb.fieldh/2-tb.r_mallet\n pos_desire(2)= tb.fieldh/2-tb.r_mallet;\nelseif pos_desire(2) < tb.r_mallet\n pos_desire(2) = tb.r_mallet;\nend\n\n%%%%%%%%%%To limit the speed of travel of the mallet%%%%%%%%%%%%%\ndelta = pos_desire - posc;\ndeltam = sqrt(delta(1)^2 + delta(2)^2);\nif deltam == 0\n posc_new = posc;\nelse\n posc_new = posc + min(deltam,tstep*maxspeed)/deltam*delta;\nend\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/39474-air-hockey-arcade/AI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019594, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3989415677005749}}
{"text": "function filter = spm_cfg_eeg_filter\n% configuration file for EEG Filtering\n%_______________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% Stefan Kiebel\n% $Id: spm_cfg_eeg_filter.m 5377 2013-04-02 17:07:57Z vladimir $\n\nrev = '$Rev: 5377 $';\n\nD = cfg_files;\nD.tag = 'D';\nD.name = 'File Name';\nD.filter = 'mat';\nD.num = [1 1];\nD.help = {'Select the EEG mat file.'};\n\ntype = cfg_menu;\ntype.tag = 'type';\ntype.name = 'Type';\ntype.labels = {'Butterworth', 'FIR'};\ntype.values = {'butterworth', 'fir'};\ntype.val = {'butterworth'};\ntype.help = {'Select the filter typee.'};\n\nband = cfg_menu;\nband.tag = 'band';\nband.name = 'Band';\nband.labels = {'Lowpass', 'Highpass', 'Bandpass', 'Stopband'};\nband.values = {'low' 'high' 'bandpass' 'stop'};\nband.val = {'low'};\nband.help = {'Select the filter band.'};\n\nfreq = cfg_entry;\nfreq.tag = 'freq';\nfreq.name = 'Cutoff(s)';\nfreq.strtype = 'r';\nfreq.num = [1 inf];\nfreq.help = {'Enter the filter cutoff'};\n\ndir = cfg_menu;\ndir.tag = 'dir';\ndir.name = 'Direction';\ndir.labels = {'Zero phase', 'Forward', 'Backward'};\ndir.values = {'twopass', 'onepass', 'onepass-reverse'};\ndir.val = {'twopass'};\ndir.help = {'Select the filter direction.'};\n\norder = cfg_entry;\norder.tag = 'order';\norder.name = 'Order';\norder.val = {5};\norder.strtype = 'n';\norder.num = [1 1];\norder.help = {'Enter the filter order'};\n\nprefix = cfg_entry;\nprefix.tag = 'prefix';\nprefix.name = 'Filename Prefix';\nprefix.help = {'Specify the string to be prepended to the filenames of the filtered dataset. Default prefix is ''f''.'};\nprefix.strtype = 's';\nprefix.num = [1 Inf];\nprefix.val = {'f'};\n\nfilter = cfg_exbranch;\nfilter.tag = 'filter';\nfilter.name = 'Filter';\nfilter.val = {D type band freq dir order, prefix};\nfilter.help = {'Filters EEG/MEG data.'};\nfilter.prog = @eeg_filter;\nfilter.vout = @vout_eeg_filter;\nfilter.modality = {'EEG'};\n\nfunction out = eeg_filter(job)\n% construct the S struct\nS = job;\nS.D = S.D{1};\n\nout.D = spm_eeg_filter(S);\nout.Dfname = {fullfile(out.D.path, out.D.fname)};\n\nfunction dep = vout_eeg_filter(job)\n% Output is always in field \"D\", no matter how job is structured\ndep = cfg_dep;\ndep.sname = 'Filtered Data';\n% reference field \"D\" from output\ndep.src_output = substruct('.','D');\n% this can be entered into any evaluated input\ndep.tgt_spec = cfg_findspec({{'strtype','e'}});\n\ndep(2) = cfg_dep;\ndep(2).sname = 'Filtered Datafile';\n% reference field \"Dfname\" from output\ndep(2).src_output = substruct('.','Dfname');\n% this can be entered into any file selector\ndep(2).tgt_spec = cfg_findspec({{'filter','mat'}});\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/config/spm_cfg_eeg_filter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3989415615222409}}
{"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 [calculation_times]=PIVlab_commandline_parallel_speed(directory,cpu_core_number)\n\nnr_of_cores =cpu_core_number; % integer, 1 means single core, greater than 1 means parallel\nif nr_of_cores > 1\n\ttry\n\t\tlocal_cluster=parcluster('local'); % single node\n\t\tcorenum = local_cluster.NumWorkers ; % fix : get the number of cores available\n\tcatch\n\t\twarning('on');\n\t\twarning('parallel local cluster can not be created, assigning number of cores to 1');\n\t\tnr_of_cores = 1;\n\tend\nend\n\nif nr_of_cores > 1\n\tif pivparpool('size')~=nr_of_cores\n\t\tpivparpool('close');\n\t\tpivparpool('open',nr_of_cores);\n\tend\nend\n\n%% Create list of images inside user specified directory\n\n% default directory: PIVlab/Examples\naddpath(fileparts(mfilename('fullpath')));\n%disp(fileparts(mfilename('fullpath')))\n\nsuffix='*.jpg'; %*.bmp or *.tif or *.jpg or *.tiff or *.jpeg\n%disp(['Looking for ' suffix ' files in the selected directory.']);\ndirec = dir([directory,filesep,suffix]); filenames={};\n[filenames{1:length(direc),1}] = deal(direc.name);\nfilenames = sortrows(filenames); %sort all image files\namount = length(filenames);\n\n%% Standard PIV Settings\ns = cell(15,2); % To make it more readable, let's create a \"settings table\"\n%Parameter %Setting %Options\ns{1,1}= 'Int. area 1'; s{1,2}=128; % window size of first pass\ns{2,1}= 'Step size 1'; s{2,2}=64; % step of first pass\ns{3,1}= 'Subpix. finder'; s{3,2}=1; % 1 = 3point Gauss, 2 = 2D Gauss\ns{4,1}= 'Mask'; s{4,2}=[]; % If needed, generate via: imagesc(image); [temp,Mask{1,1},Mask{1,2}]=roipoly;\ns{5,1}= 'ROI'; s{5,2}=[]; % Region of interest: [x,y,width,height] in pixels, may be left empty\ns{6,1}= 'Nr. of passes'; s{6,2}=2; % 1-4 nr. of passes\ns{7,1}= 'Int. area 2'; s{7,2}=64; % second pass window size\ns{8,1}= 'Int. area 3'; s{8,2}=16; % third pass window size\ns{9,1}= 'Int. area 4'; s{9,2}=16; % fourth pass window size\ns{10,1}='Window deformation'; s{10,2}='*linear'; % '*spline' is more accurate, but slower\ns{11,1}='Repeated Correlation'; s{11,2}=0; % 0 or 1 : Repeat the correlation four times and multiply the correlation matrices.\ns{12,1}='Disable Autocorrelation'; s{12,2}=0; % 0 or 1 : Disable Autocorrelation in the first pass.\ns{13,1}='Correlation style'; s{13,2}=0; % 0 or 1 : Use circular correlation (0) or linear correlation (1).\ns{14,1}='Repeat last pass'; s{14,2}=0; % 0 or 1 : Repeat the last pass of a multipass analyis\ns{15,1}='Last pass quality slope'; s{15,2}=0.025; % Repetitions of last pass will stop when the average difference to the previous pass is less than this number.\n\n\n%% Standard image preprocessing settings\np = cell(10,1);\n%Parameter %Setting %Options\np{1,1}= 'ROI'; p{1,2}=s{5,2}; % same as in PIV settings\np{2,1}= 'CLAHE'; p{2,2}=1; % 1 = enable CLAHE (contrast enhancement), 0 = disable\np{3,1}= 'CLAHE size'; p{3,2}=50; % CLAHE window size\np{4,1}= 'Highpass'; p{4,2}=0; % 1 = enable highpass, 0 = disable\np{5,1}= 'Highpass size'; p{5,2}=15; % highpass size\np{6,1}= 'Clipping'; p{6,2}=0; % 1 = enable clipping, 0 = disable\np{7,1}= 'Wiener'; p{7,2}=0; % 1 = enable Wiener2 adaptive denoise filter, 0 = disable\np{8,1}= 'Wiener size'; p{8,2}=3; % Wiener2 window size\np{9,1}= 'Minimum intensity'; p{9,2}=0.0; % Minimum intensity of input image (0 = no change)\np{10,1}='Maximum intensity'; p{10,2}=1.0; % Maximum intensity on input image (1 = no change)\n\n%% other settings\npairwise = 1; % 0 for [A+B], [B+C], [C+D]... sequencing style, and 1 for [A+B], [C+D], [E+F]... sequencing style\n\n%% PIV analysis loop\nif pairwise == 1\n\tif mod(amount,2) == 1 %Uneven number of images?\n\t\tdisp('Image folder should contain an even number of images.')\n\t\t%remove last image from list\n\t\tamount=amount-1;\n\t\tfilenames(size(filenames,1))=[];\n\tend\n\t\n\t%disp(['Found ' num2str(amount) ' images (' num2str(amount/2) ' image pairs).'])\n\tx=cell(amount/2,1);\n\ty=x;\n\tu=x;\n\tv=x;\nelse\n\t%disp(['Found ' num2str(amount) ' images'])\n\tx=cell(amount-1,1);\n\ty=x;\n\tu=x;\n\tv=x;\nend\n\ntypevector=x; %typevector will be 1 for regular vectors, 0 for masked areas\ncorrelation_map=x; % correlation coefficient\n\n%% Pre-load the image names out side of the parallelizable loop\nslicedfilename1=cell(0);\nslicedfilename2=cell(0);\nj = 1;\nfor i=1:1+pairwise:amount-1\n\tslicedfilename1{j}=filenames{i}; % begin\n\tslicedfilename2{j}=filenames{i+1}; % end\n\tj = j+1;\nend\n\ndummy=imread(fullfile(directory,filenames{1}));\ndisp([' Current image size: ' num2str(size(dummy,1)) ' px'])\n\n\ntstart=tic;\n%% Main PIV analysis loop:\n% parallel\ndisp('Please wait....')\nif nr_of_cores > 1\n\t\n\t\n\t\n\tparfor i=1:size(slicedfilename1,2) % index must increment by 1\n\t\t\n\t\t[x{i}, y{i}, u{i}, v{i}, typevector{i},correlation_map{i}] = ...\n\t\t\tpiv_analysis(directory, slicedfilename1{i}, slicedfilename2{i},p,s,nr_of_cores,false);\n\tend\nelse % sequential loop\n\t\n\tfor i=1:size(slicedfilename1,2) % index must increment by 1\n\t\t\n\t\t[x{i}, y{i}, u{i}, v{i}, typevector{i},correlation_map{i}] = ...\n\t\t\tpiv_analysis(directory, slicedfilename1{i}, slicedfilename2{i},p,s,nr_of_cores,false);\n\t\t\n\t\t%disp([int2str((i+1)/amount*100) ' %']);\n\t\t\n\tend\nend\n\n\n%% PIV postprocessing loop\n% Standard image post processing settings\n\nr = cell(6,1);\n%Parameter %Setting %Options\nr{1,1}= 'Calibration factor, 1 for uncalibrated data'; r{1,2}=1; % Calibration factor for u\nr{2,1}= 'Calibration factor, 1 for uncalibrated data'; r{2,2}=1; % Calibration factor for v\nr{3,1}= 'Valid velocities [u_min; u_max; v_min; v_max]'; r{3,2}=[-50; 50; -50; 50]; % Maximum allowed velocities, for uncalibrated data: maximum displacement in pixels\nr{4,1}= 'Stdev check?'; r{4,2}=1; % 1 = enable global standard deviation test\nr{5,1}= 'Stdev threshold'; r{5,2}=7; % Threshold for the stdev test\nr{6,1}= 'Local median check?'; r{6,2}=1; % 1 = enable local median test\nr{7,1}= 'Local median threshold'; r{7,2}=3; % Threshold for the local median test\n\nu_filt=cell(size(u));\nv_filt=cell(size(v));\ntypevector_filt=typevector;\n\nif nr_of_cores >1 % parallel\n\t\n\t\n\tif pivparpool('size')~=nr_of_cores\n\t\tpivparpool('open',nr_of_cores);\n\tend\n\t\n\t\n\tparfor PIVresult=1:size(x,1)\n\t\t\n\t\t[u_filt{PIVresult,1}, v_filt{PIVresult,1},typevector_filt{PIVresult,1}]= ...\n\t\t\tpost_proc_wrapper(u{PIVresult,1},v{PIVresult,1},typevector{PIVresult,1},r,true);\n\t\t\n\tend\n\t\nelse % sequential loop\n\t\n\tfor PIVresult=1:size(x,1)\n\t\t\n\t\t[u_filt{PIVresult,1}, v_filt{PIVresult,1},typevector_filt{PIVresult,1}]= ...\n\t\t\tpost_proc_wrapper(u{PIVresult,1},v{PIVresult,1},typevector{PIVresult,1},r,true);\n\t\t\n\tend\n\t\nend\ncalculation_times=toc(tstart);\n%% clean up parallel pool, and cluster\n%{\nif nr_of_cores >1 % parallel\n\tpoolobj = gcp('nocreate'); % GET the current parallel pool\n\tif ~isempty(poolobj ); delete(poolobj );end\n\tclear local_cluster;\nend\n%}\n%%\n%save(fullfile(directory, [filenames{1} '_' filenames{end} '_' num2str(amount) '_frames_result_.mat']));\n\n%%\n%clearvars -except p s r x y u v typevector directory filenames u_filt v_filt typevector_filt correlation_map\ndisp('DONE.')\n\nend\nfunction [u_filt, v_filt,typevector_filt] = post_proc_wrapper(u,v,typevector,post_proc_setting,paint_nan)\n% wrapper function for PIVlab_postproc\n\n% INPUT\n% u, v: u and v components of vector fields\n% typevector: type vector\n% post_proc_setting: post processing setting\n% paint_nan: bool, whether to interpolate missing data\n\n% OUTPUT\n% u_filt, v_filt: post-processed u and v components of vector fields\n% typevector_filt: post-processed type vector\n\n\n[u_filt,v_filt] = PIVlab_postproc(u,v, ...\n\tpost_proc_setting{1,2},...\n\tpost_proc_setting{2,2},...\n\tpost_proc_setting{3,2},...\n\tpost_proc_setting{4,2},...\n\tpost_proc_setting{5,2},...\n\tpost_proc_setting{6,2},...\n\tpost_proc_setting{7,2});\n\ntypevector_filt = typevector; % initiate\ntypevector_filt(isnan(u_filt))=2;\ntypevector_filt(isnan(v_filt))=2;\ntypevector_filt(typevector==0)=0; %restores typevector for mask\n\nif paint_nan\n\tu_filt=inpaint_nans(u_filt,4);\n\tv_filt=inpaint_nans(v_filt,4);\nend\n\n\nend\n\n", "meta": {"author": "Shrediquette", "repo": "PIVlab", "sha": "2db174a35e8f77cc2ecbee99f1516b8a222492a0", "save_path": "github-repos/MATLAB/Shrediquette-PIVlab", "path": "github-repos/MATLAB/Shrediquette-PIVlab/PIVlab-2db174a35e8f77cc2ecbee99f1516b8a222492a0/test_parallel_performance/PIVlab_commandline_parallel_speed.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.3989057089363508}}
{"text": "% Author: Ricardo Baptista and Matthias Poloczek\n% Date: June 2018\n%\n% See LICENSE.md for copyright information\n%\n\nfunction models = sample_models(n_models, n_vars, values)\n% SAMPLE_MODELS: Sample candidate model vectors with categorical values\n%\n% Inputs: n_models - number of vectors to return\n% n_vars - number of variables for each vector\n% values - {n_vars x 1} cell - numeric variables for each dimension\n\n% check values and default to binary if not specified\nif nargin < 3\n\tvalues = repmat({[0,1]},n_vars,1);\nend\n\n% check if n_vars and values have the same dimension\nif length(values) ~= n_vars\n error('Number of variables does not match size of values cell')\nend\n\n% Generate matrix of zeros to store models\nmodels = zeros(n_models, n_vars);\n\n% Construct model vectors by sampling each dimension independently\n% and with replacement\nfor j=1:n_vars\n\tmodels(:,j) = randsample(values{j}, n_models, true);\nend\n\n% -- END OF FILE --", "meta": {"author": "baptistar", "repo": "BOCS", "sha": "fef0d4e34e376e8bb0dae9955d70c2155530b9eb", "save_path": "github-repos/MATLAB/baptistar-BOCS", "path": "github-repos/MATLAB/baptistar-BOCS/BOCS-fef0d4e34e376e8bb0dae9955d70c2155530b9eb/tools/sample_models.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.39890570013363774}}
{"text": "%{\nAuthors:\nJonatas Lopes de Paiva\nClaudio Fabiano Motta Toledo\nHelio Pedrini\n\n%}\n\nfunction pop = createPop(sizePop, img, denoisedImages, beta, lambda )\n\npopulation(sizePop).fitness = 0;\npopulation(sizePop).cromo = [];\npopulation(sizePop).id = '';\n\nmut1 = denoisedImages(1).img;\nmut2 = denoisedImages(2).img;\nmut3 = denoisedImages(3).img;\n\nfit1 = calcFitness(mut1, img, beta, lambda);\nfit2 = calcFitness(mut2, img, beta, lambda);\nfit3 = calcFitness(mut3, img, beta, lambda);\n\npopulation(1).fitness = fit1;\npopulation(1).cromo = mut1;\npopulation(1).id = char(java.util.UUID.randomUUID.toString);\n\npopulation(2).fitness = fit2;\npopulation(2).cromo = mut2;\npopulation(2).id = char(java.util.UUID.randomUUID.toString);\n\npopulation(3).fitness = fit3;\npopulation(3).cromo = mut3;\npopulation(3).id = char(java.util.UUID.randomUUID.toString);\n\nfor i = 4:sizePop\n tmp = denoisedImages(randi(3)).img;\n population(i).cromo = mutation(tmp);\n population(i).fitness = calcFitness(population(i).cromo, img, beta, lambda);\n population(i).id = char(java.util.UUID.randomUUID.toString);\nend\n\npop = arrangePop(population);\n\nend\n\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u53bb\u566a\u7b97\u6cd5/hga_image_denoising-master/code/createPop.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.39890570013363774}}
{"text": "function out = ctranspose2x2(in)\n\n% compute ctranspose of multiple 2x2 matrices, input is 2x2xN\n\nout = conj(in);\nout(1,2,:,:) = conj(in(2,1,:,:));\nout(2,1,:,:) = conj(in(1,2,:,:));\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/connectivity/private/ctranspose2x2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.3989057000471937}}
{"text": "% PRTBRV - PRT Bayesian Random Variable Class\n% Abstract Methods:\n% nDimensions\n\n\n\n\n\n\n\nclassdef prtBrv < prtAction\n methods (Abstract)\n self = estimateParameters(self, priorSelf, x)\n y = predictivePdf(self, x)\n y = predictiveLogPdf(self, x)\n \n d = getNumDimensions(self)\n \n self = initialize(self, x)\n end\n \n methods\n % Optional methods that would be nice to have\n % You don't have to implement these but you are welcome to some\n % types of processing for example VB with \n % calculateNegativeFreeEnergy = true, might require some of these\n function kld = conjugateKld(self, prior) %#ok\n missingMethodError(self,'conjugateKld')\n end\n function x = posteriorMeanDraw(self, n, varargin) %#ok\n missingMethodError(self,'posteriorMeanDraw')\n end \n function s = posteriorMeanStruct(self) %#ok\n missingMethodError(self,'posteriorMeanStruct')\n end\n function plotCollection(selfVec,colors) %#ok\n missingMethodError(selfVec(1),'plotCollection') \n end\n function val = plotLimits(self) %#ok\n missingMethodError(self,'plotLimits') \n end\n %function plot(self)\n % plotCollection(self);\n %end\n end\n \n \n % All prtBrv's get the property nDimensions\n % For a particular subclass getNumDimensions must be implemented\n properties (Dependent)\n nDimensions\n end\n methods \n function val = get.nDimensions(self)\n val = zeros(size(self));\n for iRv = 1:numel(self)\n val(iRv) = self(iRv).getNumDimensions();\n end\n end\n end\n \n % Because we are a prtAction we also must implement something like this\n \n %%% properties (SetAccess=private)\n %%% name = 'Maximum a Posteriori' % Maximum a Posteriori\n %%% nameAbbreviation = 'MAP' % MAP\n %%% isNativeMary = true; % True\n %%% end\n \n % For prtAction, we also must implement trainAction() and runAction()\n methods (Access = protected, Hidden = true)\n function self = trainAction(self, ds)\n self = estimateParameters(self, ds); \n end\n \n function ds = runAction(self, ds)\n ds = ds.setObservations(self.predictiveLogPdf(ds.getObservations));\n end\n end\n \n methods (Access = 'protected', Hidden = true)\n function missingMethodError(self,methodName) %#ok\n error('The method %s is not defined for this prtBrv object',methodName);\n end\n \n function self = constructorInputParse(self,varargin)\n \n nIn = length(varargin);\n\n % Quick Exit for the zero input constructor\n if nIn == 0\n return\n elseif mod(nIn,2)\n error('prt:prtBrv:constructorInputParse','Inputs must be supplied by as string/value pairs');\n end\n \n self = prtUtilAssignStringValuePairs(self, varargin{:});\n\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/]beta/brv/prtBrv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.39886039958082553}}
{"text": "%GOBJ_POLYGON Create polygon geometry object.\n%\n% [ GOBJ ] = GOBJ_POLYGON( P, TAG ) Creates a polygon\n% geometry object. Accepts the following input parameters.\n%\n% Parameter Value/{Default} Description\n% -----------------------------------------------------------------------------------\n% p array {[0 0;1 0;0 1]} Polygon vertex points\n% tag string {P1} Geometry object tag/name\n\n% Copyright 2013-2022 Precise Simulation, Ltd.\n", "meta": {"author": "precise-simulation", "repo": "featool-multiphysics", "sha": "861c771adda317a9f091263d16dca060116bd516", "save_path": "github-repos/MATLAB/precise-simulation-featool-multiphysics", "path": "github-repos/MATLAB/precise-simulation-featool-multiphysics/featool-multiphysics-861c771adda317a9f091263d16dca060116bd516/geom/gobj_polygon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.6261241842048092, "lm_q1q2_score": 0.3988603865073714}}
{"text": "%#eml\nfunction [min,med,max] = get_median(inbuf)\n\nnumpixels = length(inbuf);\n\ntbuf = inbuf;\n\nfor ii=eml.unroll(1:numpixels)\n if bitand(ii,uint32(1)) == 1 \n tbuf = compare_stage1(tbuf);\n else\n tbuf = compare_stage2(tbuf);\n end\nend\n\nmin = tbuf(1);\nmed = tbuf(ceil(numpixels/2));\nmax = tbuf(numpixels);\n\nend\n\nfunction outbuf = compare_stage1(inbuf)\nnumpixels = length(inbuf);\ntbuf = compare_stage(inbuf(1:numpixels-1));\noutbuf = [tbuf(:)' inbuf(numpixels)];\nend\n\nfunction outbuf = compare_stage2(inbuf)\nnumpixels = length(inbuf);\ntbuf = compare_stage(inbuf(2:numpixels));\noutbuf = [inbuf(1) tbuf(:)'];\nend\n\nfunction [outbuf] = compare_stage(inbuf)\n\nstep = 2;\nnumpixels = length(inbuf);\n\noutbuf = inbuf;\n\nfor ii=eml.unroll(1:step:numpixels)\n t = compare_pixels([inbuf(ii), inbuf(ii+1)]);\n outbuf(ii) = t(1);\n outbuf(ii+1) = t(2);\nend\n\nend\n\nfunction outbuf = compare_pixels(inbuf)\nif (inbuf(1) > inbuf(2))\n outbuf = [inbuf(1), inbuf(2)];\nelse\n outbuf = [inbuf(2), inbuf(1)];\nend\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/18728-adaptive-median-filter-using-embedded-matlab/get_median.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.3988603734339173}}
{"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 [xpad, nup, n1, n2] = padsignal(x, padtype)\n\n[nup, n1, n2] = p2up(length(x));\n\nxl = padarray(x(:), n1, padtype, 'pre');\nxr = padarray(x(:), n2, padtype, 'post');\n\nxpad = [xl(1:n1); x(:); xr(end-n2+1:end)];\n", "meta": {"author": "HeLiangHIT", "repo": "time_frequency", "sha": "09c2abe92355ff5cd867bdb169229682e9d7af7c", "save_path": "github-repos/MATLAB/HeLiangHIT-time_frequency", "path": "github-repos/MATLAB/HeLiangHIT-time_frequency/time_frequency-09c2abe92355ff5cd867bdb169229682e9d7af7c/tf_tool_box/synchrosqueezing/synchrosqueezing/padsignal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.39876977001835007}}
{"text": "function x = testMaps()\n%tests the functionality of the functions in testMaps especially drawLine,\n% drawConc, drawFlux\n%\n% testMaps\n%\n%\n%\n\noriFolder = pwd;\n\nmFilePath = mfilename('fullpath');\ncd(mFilePath(1:end-length(mfilename)));\n\nmapCoordinateFilename='ecoli_core_map.txt';\n\nmap = readCbMap(mapCoordinateFilename);\nload('ecoli_core_model.mat');\nsol = optimizeCbModel(model);\nglobal CB_MAP_OUTPUT\nif ~strcmp(CB_MAP_OUTPUT,'svg')\n f = figure;\nend\ndrawCbMap(map);\n\n%tests drawConc with zero concentrations of metabolites\ndisp('Testing drawConc with zero concentrations');\nconc = zeros(size(model.metNames,1), 1);\ndrawConc(map, model, conc);\ndisp(' ');\ndisp(' ');\n\ndisp('Testing drawConc with non-zero concentrations');\nconc = rand(size(model.metNames,1),1);\ndrawConc(map, model, conc);\ndisp(' ');\ndisp(' ');\n\n%tests drawFlux with zero fluxes\ndisp('Testing drawFlux with zero flux');\nflux = zeros(size(model.rxns,1), 1);\ndrawFlux(map, model, flux);\ndisp(' ');\ndisp(' ');\n\n%tests drawFlux with non-zero fluxes w/ reaction with zero flux set to\n%width of 1\ndisp('Testing drawFlux with non-zero flux');\nflux = sol.x;\ndrawFlux(map, model, flux, [],'zeroFluxWidth',1);\ndisp(' ');\ndisp(' ');\n\n%tests drawFluxVariablity with enlarged arrowheads to denote flux\n%directionality\nload('testMapsData.mat','minFlux','maxFlux');\ndisplay('Testing drawFluxVariability')\ndrawFluxVariability(map,model,minFlux,maxFlux,[],'rxnDirMultiplier',2.5);\ndisplay(' ');\ndisplay(' ');\n\n\nx=1;\nif ~strcmp(CB_MAP_OUTPUT,'svg')\n close(f);\nend\ncd(oriFolder);\n\nend", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/test/additionalTests/testMaps/testMaps.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.39876976574757134}}
{"text": "function data=syms2v(symbols,numberOfZeros)\n%% syms2v : Symbols (nRows,N) to Vector of size (1,L)\n% data=syms2v(symbols,numberOfZeros)\n%% INPUTS: symbols, and numberOfZeros; as follows\n% where L = number of the elements in the vector [data]\n%% Outputs: \n% data: is the original vector without the originally attached zeros\n[r c]=size(symbols);\nd=reshape(symbols,1,r*c);\ndata=d(1:end-numberOfZeros);", "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/36309-simulation-of-an-ofdm-system-with-the-psd/OFDM only/syms2v.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.6224593382055109, "lm_q1q2_score": 0.398769761692807}}
{"text": "% select_region.m\n\n% Copyright 2003-2010 The MathWorks, Inc.\n\nf = squeeze(uint8(mean(f,3))); %RGB color to grayscale conversion\navg = mean(f,3); %composite leaves traces of moving objects\nbg = median(double(f),3); %ensemble median average minimizes motion\n\n%difference image highlights circular path of motion\narcPath = imabsdiff(avg,bg);\nfigure, imshow(arcPath,[])\ntitle('Click-drag-release to select region of interest')\n\n% %user select region\n% h=msgbox('Select region of interest.','ROI');\n% set(h,'WindowStyle','Modal')\n% waitfor(h)\n \ndone=false;\nwhile ~done\n [subIm,roi]=imcrop;\n %wait for user to select region of interest (click-drag rubberband box)\n\n %determine corners of selected region\n x1=roi(1); x2=roi(1)+roi(3); xx=[x1 x1 x2 x2 x1];\n y1=roi(2); y2=roi(2)+roi(4); yy=[y1 y2 y2 y1 y1];\n %draw rectangle to indicate selected region\n hLine=line(xx,yy);\n title('Click inside to keep, outside to select again')\n pt=ginput(1);\n %wait for user to keep or discard selected region\n\n % check: is point inside region?\n if pt(1)>=roi(1) & pt(1)<=roi(1)+roi(3) & pt(2)>=roi(2) & pt(2)<=roi(2)+roi(4)\n done=true; %exit loop\n else\n delete(hLine) %remove previous selection\n title('Click-drag-release to select region of interest')\n %loop around to select another region\n end\nend\n\n% %display cropped region\n% imshow(subIm,'notruesize')\n% title('Selected region of interest')\n\n% %convert RGB color frames to grayscale\n% f = squeeze(mean(f,3));\n\n%crop all frames; display cropped footage\nf2 = zeros([size(subIm,1) size(subIm,2) nFrames]); %allocate for cropped footage\nshg, set(gcf,'doublebuffer','on')\nfor i=1:nFrames\n f2(:,:,i)=imcrop(f(:,:,i),roi);\n imshow(uint8(f2(:,:,i)))\n title(sprintf('Frame %d, t = %.2f sec',i,t(i)))\n drawnow, pause(0.1)\nend\nset(gcf,'doublebuffer','off')\n\nf=f2; clear f2\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/3700-gravity-measurement-case-study/Gravity Measurement/select_region.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.3987697572060137}}
{"text": "%% FUNCTION init_opts\n% initialization options for multi-task learning library\n%\n% If one of the ncessary opts are empty then it will be set to default\n% values as specified in this file.\n%\n% Table of Options. * * indicates default value.\n% FIELD DESCRIPTION\n%% Optimization options\n%\n% .max_iter Maximum iteration step number\n% *1000*\n% .tol Tolerance\n% *10e-3*\n% .tFlag Termination condition\n% 0 => change of absolute function value:\n% abs( funcVal(i)- funcVal(i-1) ) <= .tol\n% * 1 => change of relative function value:\n% abs( funcVal(i)- funcVal(i-1) )\n% <= .tol * funcVal(i-1)\n% 2 => absolute function value:\n% funcVal(end)<= .tol\n% 3 => Run the code for .maxIter iterations\n%% Starting Point\n%\n% .W0 Starting point of W.\n% Initialized according to .init.\n%\n% .C0 Starting point for the intercept C (for Logistic Loss)\n% Initialized according to .init.\n%\n% .init .init specifies how to initialize W, C.\n% 0 => .W0, C0 are set by a guess value infered from data\n% 1 => .W0 and .C0 are defined\n% * 2 => .W0= zeros(.), .C0=0 *\n%\n%% Parallel Computing\n%\n% .pFlag Enable Map-Reduce (needs Parallel Toolbox support).\n% *false*\n%\n% .pSeg_num set the number of total parallel segmentations. if the\n% number is non-positive, then current matlab pool number\n% will be used. [supported in the incoming version]\n% * pool size *\n%\n%% LICENSE\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% Copyright (C) 2011 - 2012 Jiayu Zhou and Jieping Ye\n%\n% You are suggested to first read the Manual.\n% For any problem, please contact with Jiayu Zhou via jiayu.zhou@asu.edu\n%\n% Last modified on June 21, 2012.\n%\n\nfunction opts = init_opts (opts)\n\n%% Default values\nDEFAULT_MAX_ITERATION = 1000;\nDEFAULT_TOLERANCE = 1e-4;\nMINIMUM_TOLERANCE = eps * 100;\nDEFAULT_TERMINATION_COND = 1;\nDEFAULT_INIT = 2;\nDEFAULT_PARALLEL_SWITCH = false;\n\n%% Starting Point\nif isfield(opts,'init')\n if (opts.init~=0) && (opts.init~=1) && (opts.init~=2)\n opts.init=DEFAULT_INIT; % if .init is not 0, 1, or 2, then use the default 0\n end\n \n if (~isfield(opts,'W0')) && (opts.init==1)\n opts.init=DEFAULT_INIT; % if .W0 is not defined and .init=1, set .init=0\n end\nelse\n opts.init = DEFAULT_INIT; % if .init is not specified, use \"0\"\nend\n\n%% Tolerance\nif isfield(opts, 'tol')\n % detect if the tolerance is smaller than minimum\n % tolerance allowed.\n if (opts.tol 3\n opts.tFlag=3;\n else\n opts.tFlag=floor(opts.tFlag);\n end\nelse\n opts.tFlag = DEFAULT_TERMINATION_COND;\nend\n\n%% Parallel Options\nif isfield(opts, 'pFlag')\n if opts.pFlag == true && ~exist('matlabpool', 'file')\n opts.pFlag = false;\n warning('MALSAR:PARALLEL','Parallel Toolbox is not detected, MALSAR is forced to turn off pFlag.');\n elseif opts.pFlag ~= true && opts.pFlag ~= false\n % validate the pFlag.\n opts.pFlag = DEFAULT_PARALLEL_SWITCH;\n end\nelse\n % if not set the pFlag to default.\n opts.pFlag = DEFAULT_PARALLEL_SWITCH;\nend\n\nif opts.pFlag\n % if the pFlag is checked,\n % check segmentation number.\n if isfield(opts, 'pSeg_num')\n if opts.pSeg_num < 0\n opts.pSeg_num = matlabpool('size');\n else\n opts.pSeg_num = ceil(opts.pSeg_num);\n end\n else\n opts.pSeg_num = matlabpool('size');\n end\nend\n", "meta": {"author": "jiayuzhou", "repo": "MALSAR", "sha": "fb9751594983df020ddc4f7e4a40520ee7c37989", "save_path": "github-repos/MATLAB/jiayuzhou-MALSAR", "path": "github-repos/MATLAB/jiayuzhou-MALSAR/MALSAR-fb9751594983df020ddc4f7e4a40520ee7c37989/MALSAR/utils/init_opts.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.398744530757997}}
{"text": "function [ panoout ] = combineViews( Imgs, width, height )\n%COMBINEVIEWS Combine separate views to panorama\n% Imgs: same format as separatePano\n\npanoout = zeros(height, width, size(Imgs(1).img,3));\npanowei = zeros(height, width, size(Imgs(1).img,3));\nimgNum = length(Imgs);\nfor i = 1:imgNum\n [sphereImg validMap] = ...\n im2Sphere( Imgs(i).img, Imgs(i).fov, width, height, Imgs(i).vx, Imgs(i).vy);\n sphereImg(~validMap) = 0; \n panoout = panoout + sphereImg;\n panowei = panowei + validMap;\nend\npanoout(panowei==0) = 0;\npanowei(panowei==0) = 1;\npanoout = panoout./double(panowei);\n\nend\n\n", "meta": {"author": "zouchuhang", "repo": "LayoutNet", "sha": "95293bfb8ff787dd3b02c8a52a147a703024980f", "save_path": "github-repos/MATLAB/zouchuhang-LayoutNet", "path": "github-repos/MATLAB/zouchuhang-LayoutNet/LayoutNet-95293bfb8ff787dd3b02c8a52a147a703024980f/matlab/panoContext_code/BasicFuncPano/combineViews.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.39874453075799693}}
{"text": "classdef TestPSNR\n %TestPSNR\n\n methods (Static)\n function test_1\n src1 = randi([0 255], [50 50], 'uint8');\n src2 = randi([0 255], [50 50], 'uint8');\n x = cv.PSNR(src1, src2);\n end\n\n function test_2\n src1 = randi([0 255], [50 50 3], 'uint8');\n src2 = randi([0 255], [50 50 3], 'uint8');\n x = cv.PSNR(src1, src2);\n end\n\n function test_error_argnum\n try\n cv.PSNR();\n throw('UnitTest:Fail');\n catch e\n assert(strcmp(e.identifier,'mexopencv:error'));\n end\n end\n end\n\nend\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/test/unit_tests/TestPSNR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.3986338908203138}}
{"text": "\nclear all; close all;\nI=imread('glass.png');\t\t\nJ=imcomplement(I);\t\t\t\nfigure;\nsubplot(121);\nimshow(uint8(I));\t\t\nsubplot(122);\nimshow(uint8(J));\t\n", "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/\u300aMATLAB\u56fe\u50cf\u5904\u7406\u300b\u6e90\u6587\u4ef6/\u672c\u4e66\u6e90\u6587\u4ef6/chap5/chap5_8.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.3986338908203138}}
{"text": "function varargout = dsxy2figxy(varargin)\n%DSXY2FIGXY Transform point or position from axis to figure coords\n% Transforms [axx axy] or [xypos] from axes hAx (data) coords into coords\n% wrt GCF for placing annotation objects that use figure coords into data\n% space. The annotation objects this can be used for are\n% arrow, doublearrow, textarrow\n% ellipses (coordinates must be transformed to [x, y, width, height])\n% Note that line, text, and rectangle anno objects already are placed\n% on a plot using axes coordinates and must be located within an axes.\n% Example to compute a position and apply to an annotation:\n% Example:\n% [axx axy] = ginput(2);\n% [figx figy] = getaxannopos(gca, axx, axy);\n% har = annotation('textarrow',figx,figy);\n% set(har,'String',['(' num2str(axx(2)) ',' num2str(axy(2)) ')'])\n%\n% See also annotation, plot, ginput.\n\n% Copyright 2006-2007, The MathWorks, Inc. Used by permission (see\n% http://www.mathworks.com/access/helpdesk/help/techdoc/creating_plots/\n% bquk5ia-4.html).\n\n%% Obtain arguments (only limited argument checking is performed).\n% Determine if axes handle is specified\nif length(varargin{1})== 1 && ishandle(varargin{1}) && ...\n strcmp(get(varargin{1},'type'),'axes') \n hAx = varargin{1};\n varargin = varargin(2:end);\nelse\n hAx = gca;\nend;\n% Parse either a position vector or two 2-D point tuples\nif length(varargin)==1 % Must be a 4-element POS vector\n pos = varargin{1};\nelse\n [x,y] = deal(varargin{:}); % Two tuples (start & end points)\nend\n%% Get limits\naxun = get(hAx,'Units');\nset(hAx,'Units','normalized'); % Need normaized units to do the xform\naxpos = get(hAx,'Position');\naxlim = axis(hAx); % Get the axis limits [xlim ylim (zlim)]\naxwidth = diff(axlim(1:2));\naxheight = diff(axlim(3:4));\n%% Transform data from figure space to data space\nif exist('x','var') % Transform a and return pair of points\n varargout{1} = (x-axlim(1))*axpos(3)/axwidth + axpos(1);\n varargout{2} = (y-axlim(3))*axpos(4)/axheight + axpos(2);\nelse % Transform and return a position rectangle\n pos(1) = (pos(1)-axlim(1))/axwidth*axpos(3) + axpos(1);\n pos(2) = (pos(2)-axlim(3))/axheight*axpos(4) + axpos(2);\n pos(3) = pos(3)*axpos(3)/axwidth;\n pos(4) = pos(4)*axpos(4)/axheight;\n varargout{1} = pos;\nend\n%% Restore axes units\nset(hAx,'Units',axun)\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/SuiteSparse/UFcollection/dsxy2figxy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.3986338908203138}}
{"text": "function model = modelTieParam(model, paramsList)\n\n% MODELTIEPARAM Tie parameters of a model together.\n% FORMAT\n% DESC groups of parameters of a model to be seen as one parameter\n% during optimisation of the model.\n% ARG model : the model for which parameters are being tied\n% together.\n% ARG paramsList : indices of parameteres to group together. The\n% indices are provided in a cell array. Each cell in the array\n% contains a vector of indices of parameters that should be\n% considered as one parameter. Each group of parameters in each\n% cell should obviously be mutually exclusive.\n% Alternatively each element of the cell array can be a string which\n% is interpreted as a regular expression of names of parameters\n% (as returned by modelExtractParam) to be tied.\n% RETURN model : the model with the parameters grouped together.\n%\n% SEEALSO : modelExtractParam, modeExpandParam, modelLogLikeGradients\n% \n% COPYRIGHT : Neil D. Lawrence, 2003, 2006, 2008\n%\n% MODIFICATIONS: Antti Honkela, 2009\n\n% MLTOOLS\n\nif ~isfield(model, 'paramGroups')\n if isfield(model, 'nParams')\n model.paramGroups = speye(model.nParams);\n elseif isfield(model, 'numParams')\n model.paramGroups = speye(model.numParams);\n else\n error('Model does not list number of parameters.');\n end\nend\ncolToDelete = [];\ntry,\n [params, names] = modelExtractParam(model);\ncatch\n try,\n [params, names] = kernExtractParam(model);\n catch\n names = {};\n end\nend\n\nfor i = 1:length(paramsList)\n if ischar(paramsList{i}),\n paramIndices=find(~cellfun('isempty', regexp(names, paramsList{i})));\n if isempty(paramIndices),\n warning(['No matches for parameter tie spec: ', paramsList{i}])\n end\n else\n paramIndices=sort(paramsList{i});\n end\n if any(paramIndices(1) == colToDelete)\n error('Parameter is already being tied')\n end\n\n for j = 2:length(paramIndices)\n model.paramGroups(paramIndices(j), paramIndices(1)) = 1;\n if any(paramIndices(j) == colToDelete)\n error('Parameter has already been tied')\n end\n colToDelete = [colToDelete paramIndices(j)];\n end\nend\n \nmodel.paramGroups(:, colToDelete) = [];\nif isfield(model, 'nParams')\n % Update to the new number of parameters.\n model.nParams = size(model.paramGroups, 2);\nelseif isfield(model, 'numParams')\n model.numParams = size(model.paramGroups, 2);\nend\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/mltools/modelTieParam.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.3985939026055205}}
{"text": "% DEMCMU35GPLVMVARGPLVM3 Run variational GPLVM with dynamics on CMU35 data.\n%\n% COPYRIGHT : Andreas C. Damianou, Michalis K. Titsias, 2011\n%\n% SEEALSO : demCmu35vargplvmReconstructTaylor.m\n% VARGPLVM\n\n% Fix seeds\nrandn('seed', 1e5);\nrand('seed', 1e5);\n\n% Define constants (in a manner that allows other scripts to parametrize\n% this one).\nif ~exist('experimentNo') , experimentNo = 404; end\nif ~exist('itNo') , itNo = [200 1000 1300]; end % Default: 2000\nif ~exist('indPoints') , indPoints = 100; end % Default:\nif ~exist('latentDim') , latentDim = 9; end\n% Set to 1 to use dynamics or to 0 to use the standard var-GPLVM\nif ~exist('dynUsed') , dynUsed = 1; end\n\nif ~exist('fixedBetaIters'), fixedBetaIters = 50; end % DEFAULT:\n% Set to 1 to tie the inducing points with the latent vars. X\nif ~exist('fixInd') , fixInd = 0; end\nif ~exist('baseKern') , baseKern = {'rbfard2', 'white'}; end\nif ~exist('dynamicKern') , dynamicKern = {'rbf', 'bias', 'white'}; end\nif ~exist('reconstrIters') , reconstrIters = 2000; end\nif ~exist('learnVariance'), learnVariance =0; end\n%if ~exist('vardistCovarsMult'), vardistCovarsMult=1.3; end\nif ~exist('initX'), initX ='ppca'; end\nif ~exist('doReconstr'), doReconstr=1; end\nif ~exist('optimiser', 'var'), optimiser = 'scg'; end\nif ~exist('testReoptimise', 'var'), testReoptimise = 0; end\nif ~exist('parallelVardist', 'var'), parallelVardist = false; end\n\n% Get the sequence numbers.\n[Y, lbls] = lvmLoadData('cmu35WalkJog');\nseq = cumsum(sum(lbls)) - [1:31];\n\ndataSetName = 'cmu35gplvm';\n\n\n% load data\n[Y, lbls, Ytest, lblstest] = lvmLoadData(dataSetName);\n\n\nfprintf(1,'\\n#----------------------------------------------------\\n');\nfprintf(1,'# Dataset: %s\\n',dataSetName);\nfprintf(1,'# ExperimentNo: %d\\n', experimentNo);\nfprintf(1,'# Inducing points: %d\\n',indPoints);\nfprintf(1,'# Latent dimensions: %d\\n',latentDim);\nfprintf(1,'# Iterations (with/without fixed Beta): %d / %s\\n',fixedBetaIters, num2str(itNo));\n%fprintf(1,'# VardistCovarsMult: %d\\n',vardistCovarsMult);\nfprintf(1,'# Reconstruction iterations: %d\\n', reconstrIters);\nfprintf(1,'# Dataset size used (train) : %d \\n', size(Y,1));\nfprintf(1,'# Tie Inducing points: %d\\n',fixInd);\nfprintf(1,'# InitX: %s\\n',initX);\nfprintf(1,'# Base kern: ');\ndisp(baseKern);\nfprintf(1,'# Dynamics used: %d\\n', dynUsed);\nif dynUsed\n fprintf(1,'# Dynamics kern: ');\n disp(dynamicKern);\nend\n\nfprintf(1,'#----------------------------------------------------\\n');\n\n\n\n\n\n% %%% Uncomment this code to get a subset of the sequences\n% seqFrom=2;\n% seqEnd=4;\n%\n% if seqFrom ~= 1\n% Yfrom = seq(seqFrom-1)+1;\n% else\n% Yfrom = 1;\n% end\n% Yend=seq(seqEnd);\n% Y=Y(Yfrom:Yend,:);\n% seq=seq(seqFrom:seqEnd);\n% seq=seq - ones(1,length(seq)).*(Yfrom-1);\n\n\n\n% Fix times:\nprevSeq = 1;\ntimeStampsTraining = [];\ndt=0.05;\nfor i=1:length(seq)\n t = ([0:(seq(i)-prevSeq)].*dt)';\n prevSeq = seq(i)+1;\n timeStampsTraining = [timeStampsTraining ;t];\nend;\ntimeStampsTest = ([0:size(Ytest,1)-1].*dt)';\n\n\n% Set up model\noptions = vargplvmOptions('dtcvar');\n%options.kern = {'rbfard2', 'bias', 'white'};\noptions.kern = baseKern;\noptions.numActive = indPoints; % DEfault: 100\n\noptions.optimiser = optimiser;\n\nd = size(Y, 2);\nfprintf(1,'# Creating the model...\\n');\nif fixInd\n options.fixInducing=1;\n options.fixIndices=1:indPoints;\nend\nmodel = vargplvmCreate(latentDim, d, Y, options);\nmodel = vargplvmParamInit(model, model.m, model.X);\nmodel.beta=1/(0.01*var(model.m(:)));\nmodel.vardist.covars = 0.5*ones(size(model.vardist.covars)) + 0.001*randn(size(model.vardist.covars));\n\nmodel.reconstrIters = reconstrIters;\n\n%-------- Add dynamics to the model -----\nif dynUsed\n optionsDyn.type = 'vargpTime';\n optionsDyn.t=timeStampsTraining;\n optionsDyn.inverseWidth=30;\n % optionsDyn.vardistCovars = vardistCovarsMult;\n optionsDyn.seq = seq;\n optionsDyn.learnVariance = learnVariance;\n optionsDyn.initX = initX;\n optionsDyn.regularizeMeans = 0;\n \n % Dynamic kernel:\n kern = kernCreate(t, dynamicKern); % Default: {'rbf','white','bias'}\n \n if strcmp(kern.comp{2}.type, 'white')\n kern.comp{2}.variance = 1e-2; % Usual values: 1e-1, 1e-3\n end\n \n if strcmp(kern.comp{2}.type, 'whitefixed')\n if ~exist('whiteVar')\n whiteVar = 1e-6;\n end\n kern.comp{2}.variance = whiteVar;\n fprintf(1,'# fixedwhite variance: %d\\n',whiteVar);\n end\n \n if strcmp(kern.comp{1}.type, 'rbfperiodic')\n if exist('periodicPeriod')\n kern.comp{1}.period = periodicPeriod;\n end\n fprintf(1,'# periodic period: %d\\n',kern.comp{1}.period);\n end\n \n % The following is related to the expected number of\n % zero-crossings.(larger inv.width numerator, rougher func)\n if ~strcmp(kern.comp{1}.type,'ou')\n kern.comp{1}.inverseWidth = optionsDyn.inverseWidth./(((max(t)-min(t))).^2);\n kern.comp{1}.variance = 1;\n end\n optionsDyn.kern = kern;\n \n if exist('vardistCovarsMult')\n optionsDyn.vardistCovars = vardistCovarsMult;\n end\n \n \n \n % Fill in with default values whatever is not already set\n optionsDyn = vargplvmOptionsDyn(optionsDyn);\n model = vargplvmAddDynamics(model, 'vargpTime', optionsDyn, optionsDyn.t, 0, 0,optionsDyn.seq);\n \n fprintf(1,'# Further calibration of the initial parameters...\\n');\n model = vargplvmInitDynamics(model,optionsDyn);\nend\n\nif parallelVardist\n model.vardist.parallel = true;\nend\n\n\nmodelInit = model;\n\n\n% do not learn beta for few iterations for intitilization\nif fixedBetaIters > 0\n model.learnBeta = 0; model.initVardist = 1; model.learnSigmaf = 0;\n display = 1;\n fprintf(1,'# Intitiliazing the model (fixed beta) %d iterations...\\n',fixedBetaIters);\n model = vargplvmOptimise(model, display, fixedBetaIters);\n model.fixedBetaIters = fixedBetaIters;\n disp('# Saving model after optimising beta...')\n try\n vargplvmWriteResult(model, model.type, dataSetName, experimentNo);\n catch e\n warning('Error while saving model: ')\n fprintf('%s\\n',e.message)\n end\nend\n\n% Optimise the model.\ndisplay = 1;\nmodel.learnBeta = 1; model.initVardist = 0; model.learnSigmaf = 1;\nmodel.iters=0;\n\nfor i=1:length(itNo)\n iters = itNo(i); % Default: 1000\n fprintf(1,'# Optimising the model for %d iterations (session %d)...\\n',iters,i);\n model = vargplvmOptimise(model, display, iters);\n fprintf('1/b=%.4d var(model.m)=%.4d\\n', 1/model.beta, var(model.m(:)));\n model.iters = model.iters + iters;\n model.date = date;\n % Save the results.\n fprintf(1,'# Saving model after doing %d iterations',iters)\n try\n vargplvmWriteResult(model, model.type, dataSetName, experimentNo);\n catch e\n warning('Error while saving model: ')\n fprintf('%s\\n',e.message)\n end\nend\n\n%bar(model.kern.comp{1}.inputScales)\n%prefix = 'scales';\n%saveAllOpenFigures(['Results/CMU/NEW/' num2str(experimentNo) '/'], prefix,1)\n\nif testReoptimise\n model.dynamics.reoptimise=1;\nend\n\n% Reconstruction can also be done separately calling demCmu35vargplvmReconstructTaylor\nif doReconstr\n %---- RECONSTRUCTION ---%\n save 'TEMPExperimentNo.mat' 'experimentNo'\n clear\n load 'TEMPExperimentNo'\n delete TEMPExperimentNo.mat\n fprintf('# Taylor Reconstruction for expNo:%d\\n', experimentNo);\n demCmu35vargplvmReconstructTaylor\n %prefix = [num2str(experimentNo) '/'];\n %saveAllOpenFigures('Results/CMU/NEW/', prefix,1)\nend\n\n\n%% ----------- VISUALISATION\n%{\nclear;ca\n%load('/home/andreas/SoftwareNotDrpBox/oldMatFiles/vargplvm/2/demCmu35gplvmVargplvm33.mat');\nload('/home/andreas/Dropbox/_PhD/Software/github/private/vargplvm/matlab/private/priv/matFiles/Nips11/demCmu35gplvmVargplvm33.mat');\nbaseDir = datasetsDirectory;\ndirSep = filesep;\n[Y1, lbls, Ytest, lblstest] = lvmLoadData('cmu35WalkJog', [], baseDir);\nskel = acclaimReadSkel([baseDir 'mocap' dirSep 'cmu' dirSep '35' dirSep '35.asf']);\n[tmpchan, skel] = acclaimLoadChannels([baseDir 'mocap' dirSep 'cmu' dirSep '35' dirSep '35_01.amc'], skel);\n\n\n[Y, lbls] = lvmLoadData('cmu35WalkJog');\nseq = cumsum(sum(lbls)) - [1:31];\ndataSetName = 'cmu35gplvm';\n% load data\n[Y, lbls, Ytest, lblstest] = lvmLoadData(dataSetName);\nchannels = demCmu35VargplvmLoadChannels(Y, skel);\n\nmodelTmp = model; \nmodelTmp.dynamics = [];\nlvmVisualise(modelTmp, [], 'skelVargplvmVisualise', 'skelVargplvmModify', channels, skel)\nfigure; vargplvmShowScales(model)\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/demos/demCmu35gplvmVargplvm3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.3985938956923833}}
{"text": "if 1\n % This is the setup used in the paper\n a=40;\n M=60; \n L=a*M;\n W=4;\n nrep=50;\nelse\n a=50;\n M=200; \n L=a*M; \n W=4;\n nrep=50; \n \nend;\n\nsystem('rm crossover.log');\n%for gl=M:M:20*M\nfor gl=M:M:16*M\n s=sprintf('./time_dgt_fb %i %i %i %i %i %i >> crossover.log\\n',a,M,L,W,gl,nrep);\n \n disp(s);\n system(s);\nend;\n\ns=sprintf('./time_dgt_fac %i %i %i %i %i > crossover.ref\\n',a,M,L,W,nrep);\n\ndisp(s);\nsystem(s);\n\nsystem('rm crossover_real.log');\n%for gl=M:M:20*M\nfor gl=M:M:16*M\n s=sprintf('./time_dgtreal_fb %i %i %i %i %i %i >> crossover_real.log\\n',a,M,L,W,gl,nrep);\n \n disp(s);\n system(s);\nend;\n\ns=sprintf('./time_dgtreal_fac %i %i %i %i %i > crossover_real.ref\\n',a,M,L,W,nrep);\n\ndisp(s);\nsystem(s);\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/timing/compute_crossover.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.39859389569238324}}
{"text": "function [selectedSlices, nrows, ncols] = montageDims(vw);\n%\n% [selectedSlices, nrows, ncols] = montageDims(vw);\n%\n% Return the dimensions of a montage view (for inplanes, flat\n% levels). selectedSlices is a vector of the slices currently\n% being displayed in the montage, nrows and ncols are the rows\n% and columns in the image. Takes into account an optional\n% 'columnMajor' setting, so montages can run across rows \n% or columns (though the interface to set this isn't written\n% yet).\n% \n% ras, 05/05\nviewType = viewGet(vw,'viewType');\nui = viewGet(vw,'ui');\nswitch viewType\n case 'Inplane',\n firstSlice = viewGet(vw, 'curSlice');\n nSlices = get(ui.montageSize.sliderHandle,'Value');\n selectedSlices = firstSlice:firstSlice+nSlices-1;\n case 'Flat',\n selectedSlices = getFlatLevelSlices(vw); \n nSlices = length(selectedSlices);\n otherwise,\n error('drawROIsMontage: no support for this vw type.');\nend\n\nselectedSlices = selectedSlices(selectedSlices <= viewGet(vw, 'numSlices'));\nnSlices = length(selectedSlices);\n\nif isfield(vw.ui,'settings') && isfield(vw.ui.settings,'columnMajor') ...\n && vw.ui.settings.columnMajor==1\n % montage is column-major\n\tncols = ceil(sqrt(nSlices));\n\tnrows = ceil(nSlices/ncols);\nelse\n % montage is row-major\n\tnrows = ceil(sqrt(length(selectedSlices)));\n\tncols = ceil(nSlices/nrows);\nend\n\nreturn\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/View/Montage/montageDims.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.39852653661407966}}
{"text": "function [ min_cost ] = get_min_cost( compressResultsDir, qFile, lamda, epsilon_soft )\n%GET_MIN_COST Summary of this function goes here\n% Detailed explanation goes here\n \n q_file_t = fopen(qFile);\n observe_value = fscanf(q_file_t, '%d');\n fclose(q_file_t);\n observe_value(find(observe_value > 100)) = 100; % remove some unusual counts\n q_value = (1 - mapminmax(observe_value', 0, 1))'; % actually same as in CVPR_W 2013\n \n fileExt = '*.txt';\n files = dir(fullfile(compressResultsDir,fileExt)); \n \n % get the union cost \n saved_ID = [];\n for i = 0:length(files)-1\n \n fileCnt = num2str(i);\n fileName = [compressResultsDir, fileCnt, '.txt'];\n \n file_t = fopen(fileName);\n point_ID = fscanf(file_t, '%d');\n fclose(file_t);\n \n saved_ID = union(saved_ID, point_ID);\n end\n \n % sum the q_value * if_compress\n min_cost = 0;\n for i = 1:1:length(saved_ID)\n min_cost = min_cost + q_value(saved_ID(i));\n end\n \n% % sum the soft part \n% for i = 1:length(files)\n% min_cost = min_cost + lamda*epsilon_soft(i,:);\n% end\n \nend\n\n", "meta": {"author": "HuanYin94", "repo": "map_compression", "sha": "3c126a5cc832bf51f0c313c6ad8aa58a2930312c", "save_path": "github-repos/MATLAB/HuanYin94-map_compression", "path": "github-repos/MATLAB/HuanYin94-map_compression/map_compression-3c126a5cc832bf51f0c313c6ad8aa58a2930312c/gurobi/before/q_ILP/DP_cut_run/get_min_cost.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.39852653661407966}}
{"text": "function stats = rsa_regression(obj,design,study,varargin)\n% Representational similarity-based analysis, including inferences about a stimulus/task model \n% Constructs a rep. dissim. matrix (RDM) based on spatial covariance across images.\n% Takes a stimulus/experimental design (design), which is a set of binary regressors specifying groups of images. \n% Include a second grouping variable (study) of integers coding for blocks of images to resample within.\n% The function regresses the RSA matrix on the design and returns bootstrapped \n% statistics on each design regressor. \n% This method can be used to analyze generalizability across constructs and studies. \n% e.g., see reference to Kragel et al. 2018 below. In this case, this method tests whether\n% patterns of activity in an fmri data object are generalizable across\n% different groupings specified in the matrix 'design'. 'study' is an integer\n% valued vector grouping images according to study. This script does not\n% currently implement repeated measures designs (only include one image per\n% subject). See Kragel et al. (2018) Nature Neuroscience for details.\n%\n% Usage:\n% ::\n%\n% stats = rsa_regression(obj,design);\n%\n% ..\n% Author and copyright information:\n%\n% Copyright (C) 2018 Phil Kragel\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% **obj:**\n% An image object with one or more images loaded\n%\n% **design:**\n% A binary matrix where each column corresponds to a grouping\n% variable and each row corresponds to an observation.\n%\n% :Optional inputs:\n%\n%\t**'average_Euclidean'**\n%\t\tUse Euclidean distance of the response averaged across all voxels (univariate distance)\n%\t**'euclidean'**\n%\t\tUse Euclidean distance computed using all voxels\n%\t**'cosine'**\n%\t\tCompute distance using cosine similarity computed using all voxelst\n%\t**'correlation'**\n%\t\tCompute distance using correlation distance (1 - Pearson R) computed using all voxels (default)\n% :Outputs:\n% **stats:**\n% Structure including: \n% gen_index - sample estimate of generalization indices\n% bs_gen_index - bootstrap distribution for each generalization index\n% ste - standard error of generalization index\n% Z - Z score for each parameter\n% p - p value for each parameter\n% sig - significance test at FDR q < .05\n%\n% :Examples:\n% Example 1:\n% ----------------------------------------------------------------------\n% Download images from Kragel et al. 2018 Nature Neuroscience\n% Kragel, P. A., Kano, M., Van Oudenhove, L., Ly, H. G., Dupont, P., Rubio, A., ? Wager, T. D. (2018). Generalizable representations of pain, cognitive control, and negative emotion in medial frontal cortex. Nature Neuroscience, 21(2), 283?289. doi:10.1038/s41593-017-0051-7 \n% 270 subject-level images systematically sampled from 18 studies across 3 domains\n% [data_obj, names] = load_image_set('kragel18_alldata');\n% \n% Amygdala=select_atlas_subset(load_atlas('Canlab2018'),{'Amy'});\n% masked_dat=apply_mask(data_obj,Amygdala);\n% \n% dsgn = condf2indic(ceil(data_obj.metadata_table.Studynumber/6));\n% study = data_obj.metadata_table.Studynumber;\n% stats = rsa_regression(masked_dat,dsgn,study);\n%\n% ..\n% Programmers' notes:\n% List dates and changes here, and author of changes\n% 01/08/2018, created function, Phil Kragel\n% ..\n\n\n%% convert design matrix into dissimilarity matrix\nmodelRDM=[];\nfor i=1:size(design,2) %for each specified grouping\n modelRDM(:,i)=pdist(design(:,i),'seuclidean'); %#ok<*AGROW> %compute squared euclidean distance\n modelRDM(:,i)=100000*modelRDM(:,i)/sum(modelRDM(:,i)); %normalize and scale\nend\n\n%supress distance warning - 0 value distances get removed...\nwarning('off','stats:pdist:ConstantPoints')\n\nif any(strcmp([varargin{:}],'average_Euclidean'))\n brainRDM=pdist(nanmean(obj.dat)'); %distance is based on region average\nelseif any(strcmp([varargin{:}],'euclidean'))\n brainRDM=pdist(obj.dat'); %euclidean\n\nelseif any(strcmp([varargin{:}],'cosine'))\n brainRDM=pdist(obj.dat','cosine'); %euclidean\n\nelse %default to correlation\n brainRDM=pdist(obj.dat','correlation');\nend\nbrainRDM(brainRDM<.00001)=NaN;\ngen_index= glmfit([ones(length(modelRDM),1) double(modelRDM)],brainRDM','normal','constant','off');\n\nnum_it=1000;\nbs_gen_index=zeros(num_it,size(gen_index,1));\nparfor it=1:num_it\nbs_gen_index(it,:) = random_resample_within_study(modelRDM,obj,study,varargin);\nend\n\n%compute stats from bootstrap distribution (normal approx) \nb_ste = squeeze(nanstd(bs_gen_index));\nb_mean = squeeze(nanmean(bs_gen_index));\nb_ste(b_ste == 0) = Inf;\nb_Z = b_mean ./ b_ste;\nb_P = 2 * (1 - normcdf(abs(b_Z)));\n\n% assign stats to output\nstats.gen_index=gen_index;\nstats.Z=b_Z;\nstats.p=b_P;\nstats.sig=b_P.\n\n%% -*- texinfo -*-\n%% @documentencoding UTF-8\n%% @deffn Constant eulergamma ()\n%% Return Euler--Mascheroni constant.\n%%\n%% @example\n%% @group\n%% eulergamma\n%% @result{} (sym) \u03b3\n%%\n%% vpa (eulergamma ())\n%% @result{} (sym) 0.57721566490153286060651209008240\n%% @end group\n%% @end example\n%%\n%% @seealso{catalan}\n%% @end deffn\n\n%% Author: Carn\u00eb Draug\n%% Keywords: symbolic, constants\n\nfunction g = eulergamma ()\n\n if (nargin ~= 0)\n print_usage ();\n end\n\n g = pycall_sympy__ ('return sympy.S.EulerGamma,');\nend\n\n\n%!error catalan (sym(1))\n%!assert (double (eulergamma ()) > 0.577215664901)\n%!assert (double (eulergamma ()) < 0.577215664902)\n", "meta": {"author": "cbm755", "repo": "octsympy", "sha": "c1ecd1e08f027d5101d0f4250dfc496aa98c8bcd", "save_path": "github-repos/MATLAB/cbm755-octsympy", "path": "github-repos/MATLAB/cbm755-octsympy/octsympy-c1ecd1e08f027d5101d0f4250dfc496aa98c8bcd/inst/eulergamma.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.3984685421939299}}
{"text": "function [X,labels,class_names] = ml_load_data(filename,format,label_j)\n%ML_LOAD_DATA Loads a data set in which the rows are samples and the\n%columns are features/dimensions. The last column should contain the class\n%label. If not specified \n%\n%\n%\n% input -----------------------------------------------------------------\n%\n% o filename : string, path to file\n%\n% o formate : string, [.txt,.csv,...]\n%\n% o label_j : (1 x 1), column index which containts the class labels\n%\n% output ----------------------------------------------------------------\n%\n% o X : (N x D), dataset of N samples of dimension D\n%\n% o labels : (N x 1), N labels \n%\n\ndata = [];\nif ~exist('label_j','var'), label_j = []; end\n\nif strcmp(format,'csv') == true\n\n data = readtable(filename);\n\nelseif strcmp(format,'txt') == true\n \n data = load(filename);\nelse\n warning(['No such format: ' froamt ' implemented!']); \nend\n \nif isempty(label_j)\n X = data;\nelse\n \n \n \n X = table2array(data(:,1:end-1));\n labels = table2array(data(:,end));\n class_names = unique(labels);\n \n \n % if data is string convert to numbers\n if iscellstr(X) == true\n x_unique = unique(X);\n cellfind = @(string)(@(cell_contents)(strcmp(string,cell_contents)));\n X_tmp = zeros(size(X));\n % bUnknown = false;\n \n % if sum(cellfun(cellfind('?'),x_unique)) == true, bUnknown=true;end\n \n v = 0;\n for i=1:length(x_unique)\n \n \n idx = cellfun(cellfind(x_unique{i}),X); \n \n if strcmp(x_unique{i},'?') == true\n X_tmp(idx) = -1;\n else\n X_tmp(idx) = v;\n v = v + 1;\n end \n end\n \n X = X_tmp;\n end\n \n \n % if labels are strings convert them to numbers\n if iscellstr(class_names) == true\n labels_tmp = zeros(size(labels,1),1);\n cellfind = @(string)(@(cell_contents)(strcmp(string,cell_contents)));\n \n for i=1:size(class_names,1)\n idx = cellfun(cellfind(class_names{i}),labels); \n labels_tmp(idx) = i;\n end\n \n labels = labels_tmp;\n \n end\n \n \nend\n\nend\n\n\n\n\n", "meta": {"author": "epfl-lasa", "repo": "ML_toolbox", "sha": "61cc1245a2abe0c86a737d7b48bd645b28ffebee", "save_path": "github-repos/MATLAB/epfl-lasa-ML_toolbox", "path": "github-repos/MATLAB/epfl-lasa-ML_toolbox/ML_toolbox-61cc1245a2abe0c86a737d7b48bd645b28ffebee/functions/data_loading/ml_load_data.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.3984685421939299}}
{"text": "function [uu, erriter, num, tt] = test_CMF3D\n%\n% Function test_CMF3D\n%\n% The matlab function to show how to use the functions CMF3D_Mex and CMF3D_GPU\n%\n% Before using the functions CMF3D_mex, you should compile it as follows:\n% >> mex CMF3D_mex.c\n%\n% Before using the functions CMF3D_GPU, you should compile the GPU program:\n% >> nvmex -f nvmexopts.bat CMF3D_GPU.cu -IC:\\cuda\\v4.0\\include -LC:\\cuda\\v4.0\\lib\\x64 -lcufft -lcudart\n%\n% After compilation, you can define all the parameters (penalty, C_s, C_t, para) as follows: \n% \n% - penalty: point to the edge-weight penalty parameters to\n% total-variation function.\n% \n% For the case without incorporating image-edge weights, \n% penalty is given by the constant everywhere. For the case \n% with image-edge weights, penalty is given by the pixelwise \n% weight function:\n% \n% for example, penalty(x) = b/(1 + a*| grad f(x)|) where b,a > 0 .\n% \n% - C_s: point to the capacities of source flows ps\n% \n% - C_t: point to the capacities of sink flows pt\n% \n% - para: a sequence of parameters for the algorithm\n% para[0,1,2]: rows, cols, heights of the given image\n% para[3]: the maximum iteration number\n% para[4]: the error bound for convergence\n% para[5]: cc for the step-size of augmented Lagrangian method\n% para[6]: the step-size for the graident-projection step to the\n% total-variation function. Its optimal range is [0.1, 0.17].\n% \n%\n% Example:\n% \n% >> [u, erriter, i, timet] = CMF3D_GPU(single(penalty), single(Cs), single(Ct), single(para));\n%\n% >> us = max(u, beta); % where beta in (0,1)\n%\n% >> figure, loglog(erriter,'DisplayName','erriterN');figure(gcf)\n%\n% >> isosurface(u,0.5), axis([1 rows 1 cols 1 heights]), daspect([1 1 1]);\n%\n%\n% Please email Jing Yuan (cn.yuanjing@gmail.com) for any questions, \n% suggestions and bug reports\n%\n% The Software is provided \"as is\", without warranty of any kind.\n%\n% Version 1.0\n% https://sites.google.com/site/wwwjingyuan/ \n%\n% Copyright 2011 Jing Yuan (cn.yuanjing@gmail.com) \n%\n\nnfi_data = load_nii('IM_0190_frame_01.nii');\nur = double(nfi_data.img)/255;\n%ur = ur(1:100,1:100,1:100);\n\n[rows,cols,heights] = size(ur);\n\nvarParas = [rows; cols; heights; 200; 5e-4; 0.35; 0.11];\n% para 0,1,2 - rows, cols, heights of the given image\n% para 3 - the maximum number of iterations\n% para 4 - the error bound for convergence\n% para 5 - cc for the step-size of augmented Lagrangian method\n% para 6 - the step-size for the graident-projection of p\n\npenalty = 0.2*ones(rows, cols, heights);\n\nulab(1) = 0.2;\nulab(2) = 0.7;\n\n% build up the priori L_2 data terms\nfCs = abs(ur - ulab(1));\nfCt = abs(ur - ulab(2));\n\n% ----------------------------------------------------------------------\n% Use the function CMF3D_mex to run the algorithm on CPU\n% ----------------------------------------------------------------------\n\n%[uu, erriter,num,tt] = CMF3D_mex(single(penalty), single(fCs), single(fCt), single(varParas));\n\n% ----------------------------------------------------------------------\n% Use the function CMF3D_GPU to run the algorithm on GPU\n% ----------------------------------------------------------------------\n\n[uu, erriter,num,tt] = CMF3D_GPU(single(penalty), single(fCs), single(fCt), single(varParas));", "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/34126-fast-continuous-max-flow-algorithm-to-2d3d-image-segmentation/CMF v1.0/test_CMF3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316860482762, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.39846853441161895}}
{"text": "function sparse_grid_mixed_size_tests ( )\n\n%*****************************************************************************80\n%\n%% SPARSE_GRID_MIXED_SIZE_TESTS calls SPARSE_GRID_MIXED_SIZE_TEST with various arguments.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 03 March 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Local Parameters:\n%\n% Local, real TOL, a tolerance for point equality.\n% A value of sqrt ( eps ) is reasonable, and will allow the code to\n% consolidate points which are equal, or very nearly so. A value of\n% -1.0, on the other hand, will force the code to use every point, regardless\n% of duplication.\n%\n addpath ( '../sandia_rules' );\n\n tol = sqrt ( eps );\n\n fprintf ( 1, '\\n' );\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SPARSE_GRID_MIXED_SIZE_TESTS\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, ' Call SPARSE_GRID_MIXED_SIZE_TEST with various arguments.\\n' );\n fprintf ( 1, ' All tests will use a point equality tolerance of %e\\n', tol );\n\n dim_num = 2;\n level_max_min = 0;\n level_max_max = 2;\n rule = [ 1, 1 ]';\n alpha = [ 0.0, 0.0 ]';\n beta = [ 0.0, 0.0 ]';\n sparse_grid_mixed_size_test ( dim_num, level_max_min, level_max_max, ...\n rule, alpha, beta, tol );\n\n dim_num = 2;\n level_max_min = 0;\n level_max_max = 2;\n rule = [ 1, 3 ]';\n alpha = [ 0.0, 0.0 ]';\n beta = [ 0.0, 0.0 ]';\n sparse_grid_mixed_size_test ( dim_num, level_max_min, level_max_max, ...\n rule, alpha, beta, tol );\n\n dim_num = 2;\n level_max_min = 0;\n level_max_max = 2;\n rule = [ 1, 4 ]';\n alpha = [ 0.0, 0.0 ]';\n beta = [ 0.0, 0.0 ]';\n sparse_grid_mixed_size_test ( dim_num, level_max_min, level_max_max, ...\n rule, alpha, beta, tol );\n\n dim_num = 2;\n level_max_min = 0;\n level_max_max = 2;\n rule = [ 1, 7 ]';\n alpha = [ 0.0, 0.0 ]';\n beta = [ 0.0, 0.0 ]';\n sparse_grid_mixed_size_test ( dim_num, level_max_min, level_max_max, ...\n rule, alpha, beta, tol );\n\n dim_num = 2;\n level_max_min = 0;\n level_max_max = 2;\n rule = [ 1, 8 ]';\n alpha = [ 0.0, 1.5 ]';\n beta = [ 0.0, 0.0 ]';\n sparse_grid_mixed_size_test ( dim_num, level_max_min, level_max_max, ...\n rule, alpha, beta, tol );\n\n dim_num = 2;\n level_max_min = 0;\n level_max_max = 2;\n rule = [ 2, 9 ]';\n alpha = [ 0.0, 0.5 ]';\n beta = [ 0.0, 1.5 ]';\n sparse_grid_mixed_size_test ( dim_num, level_max_min, level_max_max, ...\n rule, alpha, beta, tol );\n\n dim_num = 2;\n level_max_min = 0;\n level_max_max = 2;\n rule = [ 6, 4 ]';\n alpha = [ 2.0, 0.0 ]';\n beta = [ 0.0, 0.0 ]';\n sparse_grid_mixed_size_test ( dim_num, level_max_min, level_max_max, ...\n rule, alpha, beta, tol );\n\n dim_num = 3;\n level_max_min = 0;\n level_max_max = 2;\n rule = [ 1, 2, 5 ]';\n alpha = [ 0.0, 0.0, 0.0 ]';\n beta = [ 0.0, 0.0, 0.0 ]';\n sparse_grid_mixed_size_test ( dim_num, level_max_min, level_max_max, ...\n rule, alpha, beta, tol );\n%\n% Dimension 2, Rule 13\n%\n dim_num = 2;\n level_max_min = 0;\n level_max_max = 2;\n rule = [ 13, 13 ]';\n alpha = [ 0.0, 0.0 ]';\n beta = [ 0.0, 0.0 ]';\n sparse_grid_mixed_size_test ( dim_num, level_max_min, level_max_max, ...\n rule, alpha, beta, tol );\n%\n% Dimension 2, Rule 16\n%\n dim_num = 2;\n level_max_min = 0;\n level_max_max = 2;\n rule = [ 16, 16 ]';\n alpha = [ 0.0, 0.0 ]';\n beta = [ 0.0, 0.0 ]';\n sparse_grid_mixed_size_test ( dim_num, level_max_min, level_max_max, ...\n rule, alpha, beta, tol );\n%\n% Dimension 2, Rule 17\n%\n dim_num = 2;\n level_max_min = 0;\n level_max_max = 4;\n rule = [ 17, 17 ]';\n alpha = [ 0.0, 0.0 ]';\n beta = [ 0.0, 0.0 ]';\n sparse_grid_mixed_size_test ( dim_num, level_max_min, level_max_max, ...\n rule, alpha, beta, tol );\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SPARSE_GRID_MIXED_SIZE_TESTS\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n rmpath ( '../sandia_rules' );\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_mixed/sparse_grid_mixed_size_tests.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.6477982247516796, "lm_q1q2_score": 0.39845282086962547}}
{"text": "function [n]=nnz(a)\n% Returns TT-ranks of the given tensor in TT-format\n% [N]=NNZ(A) Returns number of non zero elements in the TT representation of A\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\nn=nnz(a.core);\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/@tt_tensor/nnz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.398452816687293}}
{"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": "function efv = pne_event_nose(cx, opt)\n%PNE_EVENT_NOSE Event function to detect the limit or nose point\n% EFV = PNE_EVENT_NOSE(CX, OPT)\n%\n% PNE_MASTER event function to detect the limit or nose point of the\n% continuation curve, based on the sign of the lambda component of the\n% tangent vector.\n%\n% Set OPT.stop_at to 'NOSE' to use this function to trigger termination\n% of the continuation at the limit or nose point.\n%\n% Inputs:\n% CX : struct containing info about current point (continuation soln)\n% OPT - PNES_MASTER options struct\n%\n% Outputs:\n% EFV : event function value\n%\n% See also PNES_MASTER, PNE_REGISTER_EVENTS, PNE_EVENT_TARGET_LAM.\n\n% MP-Opt-Model\n% Copyright (c) 2016-2021, Power Systems Engineering Research Center (PSERC)\n% by Ray Zimmerman, PSERC Cornell\n% and Shrirang Abhyankar, Argonne National Laboratory\n%\n% This file is part of MP-Opt-Model.\n% Covered by the 3-clause BSD License (see LICENSE file for details).\n% See https://github.com/MATPOWER/mp-opt-model for more info.\n\n%% event function value is dlam, the last element of the\n%% normalized tangent vector at the current soln\nefv = cx.z(end);\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/mp-opt-model/lib/pne_event_nose.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": "%% 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 [ m, n, nst, ist, jst, ast ] = st_transpose ( m, n, nst, ist, jst, ...\n ast )\n\n%*****************************************************************************80\n%\n%% ST_TRANSPOSE transposes an ST matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 July 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input/output, integer M, the number of row.\n%\n% Input/output, integer N, the number of columns.\n%\n% Input/output, integer NST, the number of nonzeros.\n%\n% Input/output, integer IST(NST), JST(NST), the row and column indices.\n%\n% Input/output, real AST(NST), the nonzero values.\n%\n t = m;\n m = n;\n n = t;\n\n t = ist(1:nst);\n ist(1:nst) = jst(1:nst);\n jst(1:nst) = t(1:nst);\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_io/st_transpose.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5544704649604274, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.39843936362519056}}
{"text": "function TP = getTransProbs (hmm)\n% Returns the transition probabilies from any state to any other state,\n% without considering the persistence probabilities (i.e. the probability\n% to remain in the same state)\n%\n% Author: Diego Vidaurre, University of Oxford (2017)\n\nTP = hmm.P;\n[K,~,Q] = size(TP);\nfor j = 1:Q\n TPj = TP(:,:,j);\n TPj(eye(K)==1) = 0;\n for k = 1:K\n TPj(k,:) = TPj(k,:) / sum(TPj(k,:)); \n end\n TP(:,:,j) = TPj; \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/analysis/getTransProbs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3984393602836625}}
{"text": "function [fidout] = improvfid(ecg,fidin,fs,fidtype,fidhelp,N2)\n%\n% OVERVIEW, This function improves the fiducial point detection for the\n% Q,R,S,Toff points in the beat variable. The improved fiducial points are\n% stored in the beato variable.\n%\n% INPUTS MANDATORY DESCRIPTION\n%\n% ecg input ecg data in num of samples by 1\n% dimensions\n% fidin fiducial point input in samples number.\n% fs sampling frequency of the input ecg data.\n% fidtype type of fiducial point input. i.e. Q, R, S or T. \n% fidhelp R peak annotations used for improving S and Q point detections.\n% N2 window size of 2*N2 is used to find improved fiducial point detection for fiducial point specified as fidtype.\n%\n% OUTPUTS\n% fidout Adjusted fiducial point location after\n% improving fiducial point detection.\n%\n% \n% REPO:\n% https://github.com/cliffordlab/PhysioNet-Cardiovascular-Signal-Toolbox\n% ORIGINAL SOURCE AND AUTHORS:\n% Written by Shamim Nemati\n% editted by Ismail Sadiq on 10/26/2019.\n%\tCOPYRIGHT (C) 2019\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. The license may be found in\n% the Documents folder of the Physionet-Cardiovascular-Signal-Toolbox. \n\nfidout=zeros(1,size(fidin,2));\n\nif (nargin<5 || isempty(fidhelp))\n Rp=[]; Sp=[];\nelseif (strcmp(fidtype,'S'))\n Rp=fidhelp; Sp=[];\nelseif (strcmp(fidtype,'T'))\n Sp = fidhelp; Rp=[];\nelse\n Rp=[]; Sp=[];\nend\n\nif (nargin<4)\n direc=mean(ecg(fidin(:,1)))-mean(ecg);\nelse\n if (strcmp(fidtype,'R'))\n direc = 1;\n elseif (strcmp(fidtype,'T') & ~isempty(fidhelp))\n direc = median(ecg(fidin))-median(ecg(Sp));\n else\n direc=-1;\n end\nend\n\nif (nargin<6)\n N2 = round(0.04*fs);\nend\n\nfor i=1:size(fidout,2)\n if (~isempty(Rp) & fidin(i)>Rp(i))%S\n upper = min(fidin(i)+N2,Rp(i)+2*N2+10);\n %upper=fidin(i)+N2;\n v=ecg(Rp(i):upper)';% if there's a R right before use it\n else\n v=ecg(fidin(i)-N2:fidin(i)+N2)';\n end\n vi=v;\n if direc>0\n [val,ind]=max(vi);\n fidout(i)=(fidin(i)-N2-1)+ind;\n else\n [val,ind]=min(vi);\n if (~isempty(Rp) & fidin(i)>Rp(i))%S\n fidout(i)=Rp(i)-1+ind;\n else\n fidout(i)=(fidin(i)-N2-1)+ind;\n end\n end\nend\n\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/ECG_Analysis_Tools/MV/Tools/Annotation_generator/improvfid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3984393602836625}}
{"text": "function twRatio = computeTWRatio(throttle, ut, rVect, vVect, tankMasses, dryMass, stgStates, lvState, tankStates, bodyInfo, storageSoCs, powerStorageStates)\n altitude = norm(rVect) - bodyInfo.radius;\n presskPa = getPressureAtAltitude(bodyInfo, altitude); \n\n [~, totalThrust]= LaunchVehicleStateLogEntry.getTankMassFlowRatesDueToEngines(tankStates, tankMasses, stgStates, throttle, lvState, presskPa, ut, rVect, vVect, bodyInfo, [], storageSoCs, powerStorageStates, []);\n\n totalMass = (dryMass + sum(tankMasses))*1000; %kg \n totalThrust = totalThrust * 1000; % N\n\n% twRatio = computeSLThrustToWeight(bodyInfo, totalThrust, totalMass);\n twRatio = computeTrueThrustToWeight(bodyInfo, totalThrust, totalMass, altitude);\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/ksptot_lvd/misc/computeTWRatio.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7905303285397348, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.39835311054155365}}
{"text": "classdef TethaedraSubMeshConnecComputer < handle\n \n properties (Access = public)\n nSubCellNodes\n nSubCellsByElem\n end\n \n properties (Access = private)\n connecCase\n end\n \n properties (Access = private)\n nElemInCase\n cellNodes\n end\n \n methods (Access = public)\n \n function obj = TethaedraSubMeshConnecComputer(cParams)\n obj.init(cParams)\n end\n \n function compute(obj,nodes,icase)\n \n switch mode(size(nodes,2))\n case 7\n obj.nSubCellsByElem = 4;\n case 8\n obj.nSubCellsByElem = 6;\n end\n \n obj.nElemInCase = size(nodes,1);\n obj.cellNodes = nodes;\n nodesC = zeros(obj.nSubCellsByElem,obj.nSubCellNodes,obj.nElemInCase);\n isActive = true(obj.nElemInCase,1);\n switch mode(size(nodes,2))\n case 7\n [nodesT,nodesP] = obj.computeNodesTAndNodesP(icase);\n for inode = 1:obj.nSubCellNodes\n nodesC(1,inode,isActive) = nodesT(inode);\n nodesC(2,inode,isActive) = nodesP(1,inode);\n nodesC(3,inode,isActive) = nodesP(2,inode);\n nodesC(4,inode,isActive) = nodesP(3,inode);\n end\n case 8\n nodesCC = obj.computeNodesFourCutNodes(icase);\n for inode = 1:obj.nSubCellNodes\n nodesC(1,inode,isActive) = nodesCC(1,inode);\n nodesC(2,inode,isActive) = nodesCC(2,inode);\n nodesC(3,inode,isActive) = nodesCC(3,inode);\n nodesC(4,inode,isActive) = nodesCC(4,inode);\n nodesC(5,inode,isActive) = nodesCC(5,inode);\n nodesC(6,inode,isActive) = nodesCC(6,inode);\n end \n \n \n end\n obj.connecCase = nodesC;\n end\n \n function nodePartition = partition(obj,nodes)\n connec = permute(obj.connecCase,[3 1 2]);\n nodePartition = obj.initNodePartition();\n nNodesSubCell = size(nodes,2);\n for isubcell = 1:obj.nSubCellsByElem\n for inode = 1:obj.nSubCellNodes\n node = connec(:,isubcell,inode);\n ind = obj.computeAbsoluteMatrixIndex(node,nNodesSubCell);\n nodePartition(inode,isubcell,:) = nodes(ind);\n end\n end\n end\n \n end\n \n methods (Access = private)\n \n function init(obj,cParams)\n obj.nSubCellNodes = 4;\n end\n \n function nodes = computeNodesFourCutNodes(obj,icase)\n \n switch icase\n case 3\n nodes1 = obj.prismaTriangulation([1 5 6],[3 7 8]);\n nodes2 = obj.prismaTriangulation([2 5 7],[4 6 8]);\n nodes = [nodes1;nodes2];\n case 2\n nodes1 = obj.prismaTriangulation([2 7 8],[1 5 6]);\n nodes2 = obj.prismaTriangulation([5 3 7],[6 4 8]);\n nodes = [nodes1;nodes2];\n case 1\n nodes1 = obj.prismaTriangulation([4 7 8],[1 5 6]);\n nodes2 = obj.prismaTriangulation([5 2 7],[6 3 8]);\n nodes = [nodes1;nodes2];\n end\n \n \n end\n \n function [nodesT,nodesP] = computeNodesTAndNodesP(obj,icase)\n switch icase\n case 4\n nodesT = [5 6 7 4];\n nodesP = obj.prismaTriangulation([5 6 7],[1 2 3]);\n %nodesP = [1 5 6 7;1 2 7 6;1 2 3 7];\n case 3\n nodesP = [5 6 7 1 ;2 7 6 1;2 4 7 1 ];\n nodesP = obj.prismaTriangulation([5 7 6],[1 4 2]);\n nodesT = [5 7 6 3];\n \n \n %nodesP = [1 5 7 6;1 4 6 7;1 4 2 6];\n %nodesP = [5 6 7 2;1 5 7 2;4 1 7 2];\n case 2\n nodesT = [5 6 7 2];\n% nodesP = [1 5 6 7;1 4 7 6;6 1 4 3];\n nodesP = obj.prismaTriangulation([5 6 7],[1 3 4]);\n \n case 1\n nodesT = [6 7 1 5];\n% nodesP = [5 6 7 2;4 2 7 6;2 3 6 4];\n nodesP = obj.prismaTriangulation([5 7 6],[2 4 3]);\n \n end\n \n \n end\n \n function nodes = prismaTriangulation2(obj,nodesA,nodesB)\n nodes = [nodesA(1) nodesA(2) nodesA(3) nodesB(1);\n nodesA(1) nodesA(2) nodesA(3) nodesB(2);\n nodesA(1) nodesA(2) nodesA(3) nodesB(3)];\n end\n \n function nodes = prismaTriangulation(obj,nodesA,nodesB)\n nodes = [nodesB(1) nodesA(1) nodesA(2) nodesA(3);\n nodesB(1) nodesB(2) nodesA(3) nodesA(2);\n nodesB(1) nodesB(2) nodesB(3) nodesA(3)];\n end\n \n \n function c = initNodePartition(obj)\n c = zeros(obj.nSubCellNodes,obj.nSubCellsByElem,obj.nElemInCase);\n end\n \n \n function ind = computeAbsoluteMatrixIndex(obj,colums,nNodesSubCell)\n nElem = obj.nElemInCase;\n rows = (1:nElem)';\n ind = sub2ind([nElem,nNodesSubCell],rows,colums);\n end\n \n end\n \nend", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/FEM/Mesh/Unfitted/TethaedraSubMeshConnecComputer.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.39835310556796943}}
{"text": "function mObject3 = directSTRAIGHTmorphing(mObject1,mObject2,mRate,mixMethod);\n% Morphing based on direct mixing of STRAIGHT parameters\n% (Without time alignment)\n% mObject3 = directSTRAIGHTmorphing(mObject1,mObject2,mRate);\n\n% Designed and coded by Hideki Kawahara\n% 27/Feb./2005\n% Copyright(c) 2005, Hideki Kawahara\n\nif mObject1.samplingFrequency ~= mObject2.samplingFrequency\n mObject3 = [];\n return\nend;\nif mObject1.frameUpdateInterval ~= mObject2.frameUpdateInterval\n mObject3 = [];\n return\nend;\n\nnw1 = length(mObject1.F0);\nnw2 = length(mObject2.F0);\n[nr1,nc1] = size(mObject1.spectrogram);\n[nr2,nc2] = size(mObject2.spectrogram);\nnr3 = max(nr1,nr2);\nnc3 = max(max(nc1,nc2),max(nw1,nw2));\nnsg = zeros(nr3,nc3);\nnSgram = zeros(nr3,nc3);\nap = zeros(nr3,nc3);\nf0 = zeros(nc3);\nnVoice = zeros(nc3);\n\nswitch mixMethod\n case 'linear'\n nsg(1:nr1,1:nc1) = (1-mRate)*mObject1.spectrogram;\n nSgram(1:nr1,1:nc1) = nSgram(1:nr1,1:nc1)+(1-mRate);\n nsg(1:nr2,1:nc2) = mRate*mObject2.spectrogram+nsg(1:nr2,1:nc2);\n nSgram(1:nr2,1:nc2) = nSgram(1:nr2,1:nc2)+mRate;\n nsg = nsg./nSgram;\n case 'log'\n nsg(1:nr1,1:nc1) = (1-mRate)*log(mObject1.spectrogram);\n nSgram(1:nr1,1:nc1) = nSgram(1:nr1,1:nc1)+(1-mRate);\n nsg(1:nr2,1:nc2) = mRate*log(mObject2.spectrogram)+nsg(1:nr2,1:nc2);\n nSgram(1:nr2,1:nc2) = nSgram(1:nr2,1:nc2)+mRate;\n nsg = exp(nsg./nSgram);\nend;\nap(1:nr1,1:nc1) = (1-mRate)*mObject1.aperiodicityIndex;\nap(1:nr2,1:nc2) = mRate*mObject2.aperiodicityIndex+ap(1:nr2,1:nc2);\n\nf0(mObject1.F0>0) = (1-mRate)*log(mObject1.F0(mObject1.F0>0));\nnVoice(mObject1.F0>0) = nVoice(mObject1.F0>0)+(1-mRate);\nf0(mObject2.F0>0) = mRate*log(mObject2.F0(mObject2.F0>0))+f0(mObject2.F0>0);\nnVoice(mObject2.F0>0) = nVoice(mObject2.F0>0)+mRate;\nf0(nVoice>0) = exp(f0(nVoice>0)./nVoice(nVoice>0));\n\nmObject3 = createMobject;\nmObject3 = updateFieldOfMobject(mObject3,'spectrogram',nsg);\nmObject3 = updateFieldOfMobject(mObject3,'aperiodicityIndex',ap);\nmObject3 = updateFieldOfMobject(mObject3,'F0',f0);\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/morphing_src/directSTRAIGHTmorphing.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.5039061705290806, "lm_q1q2_score": 0.39835310059438517}}
{"text": "function self = reduce(self, waveType, sourcelat, sourcelon, stationlat, stationlon, varargin)\n % s.reduce('waveType', 'surface', 'waveSpeed', 2000, 'f', 2.0, );\n % s.distance and waveSpeed assumed to be in metres (m)\n % (INPUT) s.data assumed to be in nm or Pa\n % (OUTPUT) s.data in cm^2 or Pa.m\n \n % REQUIRES EXTRA PARAMETERS FOR RSAM OBJECTS\n %reduced = struct('Q', Inf, 'sourcelat', NaN, 'sourcelon', NaN, 'distance', NaN, 'waveType', '', 'isReduced', false, 'f', NaN, 'waveSpeed', NaN, 'stationlat', NaN, 'stationlon', NaN); \n %use = true;\n% REDUCED: a structure that is set is data are \"reduced\", i.e. corrected\n% for geometric spreading (and possibly attenuation)\n% Has 4 fields:\n% REDUCED.Q = the value of Q used to reduce the data\n% (Inf by default, which indicates no attenuation)\n% REDUCED.SOURCELAT = the latitude used for reducing the data\n% REDUCED.SOURCELON = the longitude used for reducing the data\n% REDUCED.STATIONLAT = the station latitude\n% REDUCED.STATIONLON = the station longitude\n% REDUCED.DISTANCE = the distance between source and\n% station in km\n% REDUCED.WAVETYPE = the wave type (body or surface)\n% assumed\n% REDUCED.F = the frequency used for surface waves\n% REDUCED.WAVESPEED = the S wave speed\n% REDUCED.ISREDUCED = True if the data are reduced\n% UNITS: the units of the data, e.g. nm / sec.\n% USE: use this rsam object in plots? \n p = inputParser;\n p.addParameter('waveSpeed', 2000);\n p.addParamter('f', 2.0);\n p.parse(varargin{:});\n\n self.reduced.waveSpeed = p.Results.waveSpeed;\n\n if self.reduced.isReduced\n disp('Data are already reduced');\n return;\n end\n\n self.reduced.distance = deg2km(distance(sourcelat, sourcelon, stationlat, stationlon)) *1000; % m\n\n switch self.units\n case 'nm' % Displacement\n % Do computation in cm\n self.data = self.data / 1e7;\n r = self.reduced.distance * 100; % cm\n ws = waveSpeed * 100; % cm/2\n self.measure = sprintf('%sR%s',self.measure(1),self.measure(2:end));\n switch self.reduced.waveType\n case 'body'\n self.data = self.data * r; % cm^2\n self.units = 'cm^2';\n case 'surface'\n wavelength = ws / p.Results.f; % cm\n try\n self.data = self.data .* sqrt(r * wavelength); % cm^2\n catch\n debug.print_debug(5, 'mean wavelength instead')\n self.data = self.data * sqrt(r * mean(wavelength)); % cm^2 \n end\n self.units = 'cm^2';\n self.reduced.isReduced = true;\n otherwise\n error(sprintf('Wave type %s not recognised'), self.reduced.waveType); \n end\n case 'Pa' % Pressure\n % Do computation in metres\n self.data = self.data * self.reduced.distance; % Pa.m \n self.units = 'Pa m';\n self.reduced.isReduced = true;\n self.measure = sprintf('%sR%s',self.measure(1),self.measure(2:end));\n otherwise\n error(sprintf('Units %s for measure %s not recognised', self.units, self.measure));\n end\n self.reduced.sourcelat = sourcelat;\n self.reduced.sourcelon = sourcelon;\n self.reduced.stationlat = stationlat;\n self.reduced.stationlon = stationlon;\n\nend", "meta": {"author": "geoscience-community-codes", "repo": "GISMO", "sha": "a4eafca9d2ac85079253510005ef00aa9998d030", "save_path": "github-repos/MATLAB/geoscience-community-codes-GISMO", "path": "github-repos/MATLAB/geoscience-community-codes-GISMO/GISMO-a4eafca9d2ac85079253510005ef00aa9998d030/core/@rsam/extensions/reduce.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3983531005943851}}
{"text": "function fact_test ( )\n\n%*****************************************************************************80\n%\n%% FACT_TEST tests the use of the MEX file FACT.C\n%\n% Discussion:\n%\n% The file fact.c is a C function which computes the factorial.\n%\n% This M file \"compiles\" fact.c, and then shows how it can be called.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 July 2006\n%\n% Author:\n%\n% John Burkardt\n%\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FACT_TEST\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, ' Demonstrate a simple use of the MEX compiler,\\n' );\n fprintf ( 1, ' which allows MATLAB to call C functions.\\n' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Get a directory listing. The file FACT.C should be there.\\n' );\n\n ls\n \n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Compile the file FACT.C.\\n' );\n\n mex fact.c\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Get a directory listing. A new file should show up,\\n' );\n fprintf ( 1, ' containing the compiled information.\\n' );\n\n ls\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Now use FACT as though it were a MATLAB M-file function.\\n' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N (N Factorial)\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : 10\n\n j = fact ( i );\n\n fprintf ( 1, ' %2d %10d\\n', i, j );\n\n end\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FACT_TEST:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( )\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\n\n \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/matlab_calls_c/fact_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819874558604, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.398226635836323}}
{"text": "function t_pf_ac(quiet)\n%T_PF_AC Tests for AC power flow solvers.\n\n% MATPOWER\n% Copyright (c) 2004-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\nif nargin < 1\n quiet = 0;\nend\n\n%% alg name check opts\ncfg = {\n {'NR', 'Newton (default, power-polar)',[] [] },\n {'NR-SP', 'Newton (power-polar)', [], [] },\n {'NR-SC', 'Newton (power-cartesian)', [], [] },\n {'NR-SH', 'Newton (power-hybrid)', [], [] },\n {'NR-IP', 'Newton (current-polar)', [], [] },\n {'NR-IC', 'Newton (current-cartesian)', [], [] },\n {'NR-IH', 'Newton (current-hybrid)', [], [] },\n {'FDXB', 'Fast Decoupled (XB)', [], [] },\n {'FDBX', 'Fast Decoupled (BX)', [], [] },\n {'GS', 'Gauss-Seidel', [], [] },\n {'ZG', 'Implicit Z-bus Gauss', [], [] },\n};\nif have_feature('mp_core')\n cfg{end+1} = {'FSOLVE', 'fsolve (power-polar)', 'fsolve', [] };\n cfg{end+1} = {'FSOLVE', 'fsolve (power-cartesian)', 'fsolve', {'pf.v_cartesian', 1} };\n cfg{end+1} = {'FSOLVE', 'fsolve (current-polar)', 'fsolve', {'pf.current_balance', 1, 'pf.tol', 1e-10} };\n cfg{end+1} = {'FSOLVE', 'fsolve (current-cartesian)', 'fsolve', {'pf.v_cartesian', 1, 'pf.current_balance', 1, 'pf.tol', 1e-10} };\n% cfg{end+1} = {'FSOLVE', 'fsolve (power-polar)', 'fsolve', struct('Algorithm', 'trust-region-dogleg') },\n% cfg{end+1} = {'FSOLVE', 'fsolve (power-polar)', 'fsolve', struct('Algorithm', 'trust-region-reflective') },\n% cfg{end+1} = {'FSOLVE', 'fsolve (power-polar)', 'fsolve', struct('Algorithm', 'levenberg-marquardt', 'TolX', 1e-11) },\nend\n% %% alg name check opts\n% cfg = {\n% {'NR', 'Newton (default, power-polar)',[] [] },\n% };\n\nntests = 48;\nt_begin(length(cfg)*ntests + 6, quiet);\n\ncasefile = 't_case9_pf';\nif quiet\n verbose = 0;\nelse\n verbose = 1;\nend\nif have_feature('octave')\n if have_feature('octave', 'vnum') >= 4\n file_in_path_warn_id = 'Octave:data-file-in-path';\n else\n file_in_path_warn_id = 'Octave:load-file-in-path';\n end\n s1 = warning('query', file_in_path_warn_id);\n warning('off', file_in_path_warn_id);\nend\nmpopt0 = mpoption('out.all', 0, 'pf.tol', 1e-9, 'verbose', 0);\nmpopt0 = mpoption(mpopt0, 'verbose', verbose);\n\n%% define named indices into bus, gen, branch 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[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[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\n%% network with islands\nmpc0 = loadcase(casefile);\nmpc0.gen(1, PG) = 60;\nmpc0.gen(1, QG) = 10;\nmpc0.gen(1, [PMIN PMAX QMIN QMAX PG QG]) = mpc0.gen(1, [PMIN PMAX QMIN QMAX PG QG]) / 2;\nmpc0.gen = [mpc0.gen(1, :); mpc0.gen];\nmpc1 = mpc0;\nmpc = mpc0;\nnb = size(mpc.bus, 1);\nmpc1.bus(:, BUS_I) = mpc1.bus(:, BUS_I) + nb;\nmpc1.branch(:, F_BUS) = mpc1.branch(:, F_BUS) + nb;\nmpc1.branch(:, T_BUS) = mpc1.branch(:, T_BUS) + nb;\nmpc1.gen(:, GEN_BUS) = mpc1.gen(:, GEN_BUS) + nb;\nmpc.bus = [mpc.bus; mpc1.bus];\nmpc.branch = [mpc.branch; mpc1.branch];\nmpc.gen = [mpc.gen; mpc1.gen];\nmpc1 = mpc;\n\n%%----- AC power flow -----\n%% get solved AC power flow case from MAT-file\nload soln9_pf; %% defines bus_soln, gen_soln, branch_soln\nsoln_vg = load('soln9_pf_vg');\n\n%% run AC PF\nfor k = 1:length(cfg)\n if ~isempty(cfg{k}{3}) && ~have_fcn(cfg{k}{3})\n t_skip(ntests, sprintf('%s not available', cfg{k}{3}));\n else\n t = sprintf('AC PF - %s : ', cfg{k}{2});\n mpopt = mpoption(mpopt0, 'pf.alg', cfg{k}{1});\n if ~isempty(cfg{k}{4}) && iscell(cfg{k}{4})\n mpopt = mpoption(mpopt, cfg{k}{4}{:});\n end\n [baseMVA, bus, gen, branch, success, et] = runpf(casefile, mpopt);\n t_ok(success, [t 'success']);\n t_is(bus, bus_soln, 6, [t 'bus']);\n t_is(gen, gen_soln, 6, [t 'gen']);\n t_is(branch, branch_soln, 6, [t 'branch']);\n\n r = runpf(casefile, mpopt);\n t_ok(r.success, [t 'success']);\n t_is(r.bus, bus_soln, 6, [t 'bus']);\n t_is(r.gen, gen_soln, 6, [t 'gen']);\n t_is(r.branch, branch_soln, 6, [t 'branch']);\n\n %% check when Vg ~= 1\n t = sprintf('%s - Vg ~= 1 : ', cfg{k}{1});\n mpopt = mpoption(mpopt, 'verbose', 0);\n mpc = loadcase(casefile);\n mpc.gen(:, VG) = [1.04; 1.025; 1.025];\n r = runpf(mpc, mpopt);\n t_ok(r.success, [t 'success']);\n t_is(r.bus, soln_vg.bus_soln, 6, [t 'bus']);\n t_is(r.gen, soln_vg.gen_soln, 6, [t 'gen']);\n t_is(r.branch, soln_vg.branch_soln, 6, [t 'branch']);\n\n %% check Qg distribution, when Qmin = Qmax\n t = sprintf('%s - check Qg : ', cfg{k}{1});\n mpc = loadcase(casefile);\n mpc.gen(1, [QG QMIN QMAX]) = [10 20 20];\n r = runpf(mpc, mpopt);\n t_ok(r.success, [t 'success']);\n t_is(r.gen(1, QG), 24.07, 2, [t 'single gen, Qmin = Qmax']);\n\n mpc.gen = [mpc.gen(1, :); mpc.gen];\n mpc.gen(1, [QMIN QMAX]) = [10 10];\n mpc.gen(2, [QMIN QMAX]) = [0 50];\n r = runpf(mpc, mpopt);\n t_ok(r.success, [t 'success']);\n t_is(r.gen(1:2, QG), [10; 14.07], 2, [t '2 gens, Qmin = Qmax for one']);\n\n mpc.gen(1, [QMIN QMAX]) = [10 10];\n mpc.gen(2, [QMIN QMAX]) = [-50 -50];\n r = runpf(mpc, mpopt);\n t_ok(r.success, [t 'success']);\n t_is(r.gen(1:2, QG), [42.03; -17.97], 2, [t '2 gens, Qmin = Qmax for both']);\n\n mpc.gen(1, [QMIN QMAX]) = [0 50];\n mpc.gen(2, [QMIN QMAX]) = [0 100];\n r = runpf(mpc, mpopt);\n t_ok(r.success, [t 'success']);\n t_is(r.gen(1:2, QG), [8.02; 16.05], 2, [t '2 gens, proportional']);\n\n mpc.gen(1, [QMIN QMAX]) = [-50 0];\n mpc.gen(2, [QMIN QMAX]) = [50 150];\n r = runpf(mpc, mpopt);\n t_ok(r.success, [t 'success']);\n t_is(r.gen(1:2, QG), [-50+8.02; 50+16.05], 2, [t '2 gens, proportional']);\n\n mpc.gen(1, [QMIN QMAX]) = [-50 Inf];\n mpc.gen(2, [QMIN QMAX]) = [50 150];\n r = runpf(mpc, mpopt);\n t_ok(r.success, [t 'success']);\n t_is(r.gen(1:2, QG), [-31.61; 55.68], 2, [t '2 gens, one infinite range']);\n\n mpc.gen(1, [QMIN QMAX]) = [-50 Inf];\n mpc.gen(2, [QMIN QMAX]) = [50 Inf];\n r = runpf(mpc, mpopt);\n t_ok(r.success, [t 'success']);\n t_is(r.gen(1:2, QG), [-33.12; 57.18], 2, [t '2 gens, both infinite range']);\n\n mpc.gen(1, [QMIN QMAX]) = [-50 Inf];\n mpc.gen(2, [QMIN QMAX]) = [-Inf 150];\n r = runpf(mpc, mpopt);\n t_ok(r.success, [t 'success']);\n t_is(r.gen(1:2, QG), [76.07; -52], 2, [t '2 gens, both infinite range']);\n\n mpc.gen(1, [QMIN QMAX]) = [-Inf Inf];\n mpc.gen(2, [QMIN QMAX]) = [-Inf Inf];\n r = runpf(mpc, mpopt);\n t_ok(r.success, [t 'success']);\n t_is(r.gen(1:2, QG), [12.03; 12.03], 2, [t '2 gens, both infinite range']);\n\n t = sprintf('%s - reactive generation allocation : ', cfg{k}{1});\n mpc = loadcase(casefile);\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\n mpc.gen = [\n\t\t1\t0\t0\t300\t-300\t1\t100\t1\t250\t10\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n\t\t2\t54\t0\t0\t-5\t1\t100\t1\t300\t10\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n\t\t2\t54\t0\t5\t-5\t1\t100\t1\t300\t10\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n\t\t2\t55\t0\t25\t 10\t1\t100\t1\t300\t10\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n\t\t30\t25\t1\t300\t-300\t1\t100\t1\t270\t10\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n\t\t30\t30\t2\t300\t-300\t1\t100\t1\t270\t10\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n\t\t30\t30\t-3\t300\t-300\t1\t100\t1\t270\t10\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0;\n ];\n mpc.bus(3, BUS_TYPE) = PQ;\n r = runpf(mpc, mpopt);\n t_ok(r.success, [t 'success']);\n t_is(r.gen(2:4, QG), [-5; -5; 10] + [1; 2; 3]*1.989129794, 7, [t 'PV bus']);\n t_is(r.gen(5:7, QG), [1; 2; -3], 8, [t 'PQ bus']);\n\n %% network with islands\n t = sprintf('%s - network w/islands : AC PF : ', cfg{k}{1});\n mpc = mpc1;\n r = runpf(mpc, mpopt);\n t_ok(r.success, [t 'success']);\n t_is(r.bus( 1:9, VA), bus_soln(:, VA), 7, [t 'voltage angles 1']);\n t_is(r.bus(10:18, VA), bus_soln(:, VA), 7, [t 'voltage angles 2']);\n Pg = [gen_soln(1, PG)-30; 30; gen_soln(2:3, PG)];\n t_is(r.gen(1:4, PG), Pg, 6, [t 'active power generation 1']);\n t_is(r.gen(5:8, PG), Pg, 6, [t 'active power generation 2']);\n\n t = sprintf('%s - all buses isolated : ', cfg{k}{1});\n mpc.bus(:, BUS_TYPE) = NONE;\n try\n r = runpf(mpc, mpopt);\n t_is(r.success, 0, 12, [t 'success = 0']);\n catch\n t_ok(0, [t 'unexpected fatal error']);\n end\n\n %% case 14 with Q limits\n t = sprintf('%s - pf.enforce_q_lims == 0 : ', cfg{k}{1});\n mpc = loadcase('case14');\n mpc.gen(1, QMIN) = -10;\n mpc.gen(:, QMAX) = [10; 30; 29; 15; 15];\n bt0 = mpc.bus(:, BUS_TYPE);\n bt = bt0;\n mpopt = mpoption(mpopt, 'pf.enforce_q_lims', 0);\n r = runpf(mpc, mpopt);\n t_ok(r.success, [t 'success']);\n t_is(r.bus(:, BUS_TYPE), bt, 12, [t 'bus type']);\n t_is(r.gen(:, QG), [-16.549300542; 43.557100134; 25.075348495; 12.730944405; 17.623451366], 6, [t 'Qg']);\n\n t = sprintf('%s - pf.enforce_q_lims == 1 : ', cfg{k}{1});\n mpopt = mpoption(mpopt, 'pf.enforce_q_lims', 1);\n r = runpf(mpc, mpopt);\n bt = bt0;\n bt([1 2 3 8]) = [PQ PQ REF PQ];\n t_is(r.success, 0, 12, [t 'success = 0']);\n t_is(r.bus(:, BUS_TYPE), bt, 12, [t 'bus type']);\n t_is(r.gen(:, QG), [-10; 30; 31.608422873; 16.420423190; 15], 4, [t 'Qg']);\n\n t = sprintf('%s - pf.enforce_q_lims == 2 : ', cfg{k}{1});\n mpopt = mpoption(mpopt, 'pf.enforce_q_lims', 2);\n r = runpf(mpc, mpopt);\n bt = bt0;\n bt([1 2 3 6 8]) = [REF PQ PQ PQ PQ];\n t_ok(r.success, [t 'success']);\n t_is(r.bus(:, BUS_TYPE), bt, 12, [t 'bus type']);\n t_is(r.gen(:, QG), [-6.30936644; 30; 29; 15; 15], 5, [t 'Qg']);\n end\nend\n\nt = sprintf('%s - pf.enforce_q_lims == 1 : ', 'NR-SP');\nmpopt = mpoption(mpopt, 'pf.alg', 'NR-SP', 'pf.tol', 1e-9);\nmpopt = mpoption(mpopt, 'pf.enforce_q_lims', 1);\nr = runpf('case14', mpopt);\nt_ok(r.success, [t 'success']);\nt_is(r.iterations, 5, 12, [t 'iterations']);\nt_is(r.bus(1, VA), 0, 12, [t 'ref bus Va = 0']);\n\nt = sprintf('%s - pf.enforce_q_lims == 1 : ', 'NR-IC');\nmpopt = mpoption(mpopt, 'pf.alg', 'NR-SP', 'pf.tol', 1e-9);\nmpopt = mpoption(mpopt, 'pf.enforce_q_lims', 1);\nr = runpf('case14', mpopt);\nt_ok(r.success, [t 'success']);\nt_is(r.iterations, 5, 12, [t 'iterations']);\nt_is(r.bus(1, VA), 0, 12, [t 'ref bus Va = 0']);\n\nt_end;\n\nif have_feature('octave')\n warning(s1.state, file_in_path_warn_id);\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/t/t_pf_ac.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.39822663074977227}}
{"text": "% SP_TO_VTK: Export to VTK format for plotting.\n%\n% sp_to_vtk (u, space, geometry, npts, filename, fieldname, [options], [lambda_lame, mu_lame])\n% sp_to_vtk (u, space, geometry, pts, filename, fieldname, [options], [lambda_lame, mu_lame])\n%\n% INPUT:\n% \n% u: vector of dof weights\n% space: object representing the space of discrete functions (see sp_scalar)\n% geometry: geometry structure (see geo_load)\n% npts: number of points along each parametric direction where to evaluate\n% pts: cell array with the coordinates along each parametric direction of the points where to evaluate\n% filename: name of the output file. \n% fieldnames: how to name the saved variables in the vtk file\n% options: cell array with the fields to plot\n% accepted options are 'value' (default), 'gradient',\n% and for vectors also 'curl', 'divergence', 'stress'\n% lambda_lame: function handle to the first Lame coefficient (only needed to compute 'stress')\n% mu_lame: function handle for the second Lame coefficient (only needed to compute 'stress')\n%\n% OUTPUT:\n%\n% none \n% \n% Copyright (C) 2009, 2010 Carlo de Falco\n% Copyright (C) 2011, 2012, 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_to_vtk (u, space, geometry, npts, filename, fieldname, varargin)\n\n [eu, F] = sp_eval (u, space, geometry, npts, varargin{:});\n\n msh_to_vtk (F, eu, filename, fieldname);\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_to_vtk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.39822662247427704}}
{"text": "function sF = mrdivide(sF,s)\n% overload the / operator, i.e. one can now write @S2Fun / 2 in order\n% to scale an S2Fun.\n%\n% Syntax\n% sF = sF / 2\n% \n% Input\n% sF - @S2Fun\n% s - constant, vector\n%\n% Output\n% sF - @S2Fun\n%\n\nif ~isnumeric(s)\n error('Second argument has to be numeric. Use ./ instead.')\nend\n\nsF = times(sF,inv(s));\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/S2Fun/@S2Fun/mrdivide.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.3982266224742769}}
{"text": "function [cm3] = ml2cm3(ml)\n% Convert volume from milliliters to cubic centimeters. \n% Chad Greene 2012\ncm3 = ml;", "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/35258-unit-converters/unit_converters/ml2cm3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.3982266183365293}}
{"text": "function x=SeamPut(x,SeamVector)\n% SEAMPUT takes as input a RGB or grayscale image and SeamVector array to\n% find the pixels contained in the seam, and to adds a seam of interpolated\n% pixels to the image. Each column of SeamVector must be a single seam.\n%\n% Author: Danny Luong\n% http://danluong.com\n%\n% Last updated: 12/20/07\n\n\n[rows cols dim]=size(x);\n[SVrows SVcols SVdim]=size(SeamVector);\n\nif rows~=SVrows\n error('SeamVector and image dimension mismatch');\nend\n\nfor k=1:SVcols\n for i=1:dim\n for j=1:rows\n if SeamVector(j,k)==1\n PutImg(j,:,i)=[x(j,1,i) x(j,1:cols,i)];\n elseif SeamVector(j,k)==cols\n PutImg(j,:,i)=[x(j,1:cols,i) x(j,cols,i)];\n else\n PutImg(j,:,i)=[x(j,1:SeamVector(j,k),i) 1/2*(x(j,SeamVector(j,k),i)+x(j,SeamVector(j,k)+1,i)) x(j,SeamVector(j,k)+1:cols,i)];\n end\n end\n end\n x=PutImg;\n clear PutImg\n [rows cols dim]=size(x);\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/18089-seam-carving-for-content-aware-image-resizing-gui-implementation-demo/MATLAB_Seam_Carving/SeamPut.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6513548511303338, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.39822661419878147}}
{"text": "function mtrTrackVis2PDB(volFile, trkFile, pdbFile)\n\n% File format conversion from the .trk file format (TrackVis) to pdb files\n%\n% Parameters\n% ----------\n% volFile: A full-path to a nifti file, from which the qform will be read \n% trkFile: The trk file to be converted. \n% pdbFile: The output. \n% \n% Returns\n% -------\n% Nothing. \n\n\n% Load vol file to get AcPc xform\nvol = niftiRead(volFile);\nxformTo = vol.qto_xyz;\nxformFrom = abs(vol.qto_ijk);\nxformFrom(1:3,4)=0;\nxformToAcPc = xformTo*xformFrom;\n\n% Get mm dimensions of image\ndim_mm = vol.dim(:).*abs(diag(vol.qto_xyz(1:3,1:3)));\nclear vol;\n\n% Load trks file\nfg = read_trk_to_fg(trkFile);\n\n% Remove really short fibers (<10 points)\n%fg = dtiCleanFibers(fg, [], [], 11)\n\nfg = dtiXformFiberCoords(fg,xformToAcPc);\nfg = dtiClearQuenchStats(fg);\nfg = dtiCreateQuenchStats(fg,'Length','Length', 1);\nmtrExportFibers(fg,pdbFile,eye(4));\n\nreturn;\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/tractography/contrack/metrotrac/mtrTrackVis2PDB.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3981400300429889}}
{"text": "function [results, init_target_sz] = tracker(params)\n\n\n%% Initialisation\n% Get sequence information\n[seq, im] = get_sequence_info(params.seq);\nparams = rmfield(params, 'seq');\nif isempty(im)\n seq.rect_position = [];\n [~, results] = get_sequence_results(seq);\n return;\nend\n\n% Initialise position\npos = seq.init_pos(:)';\ntarget_sz = seq.init_sz(:)';\nparams.init_sz = target_sz;\n\n% Feature settings and default parameters\nfeatures = params.t_features;\nparams = init_default_params(params);\nparams.use_mexResize = true;\n\n% Global feature parameters\nif isfield(params, 't_global')\n global_fparams = params.t_global;\nelse\n global_fparams = [];\nend\nglobal_fparams.use_gpu = params.use_gpu;\nglobal_fparams.gpu_id = params.gpu_id;\nglobal_fparams.use_mexResize = true;\n\n% Data types\nif params.use_gpu\n params.data_type = zeros(1, 'single', 'gpuArray');\nelse\n params.data_type = zeros(1, 'single');\nend\nparams.data_type_complex = complex(params.data_type);\nglobal_fparams.data_type = params.data_type;\n\ninit_target_sz = target_sz;\n\n% Check if color image\nif size(im,3) == 3\n if all(all(im(:,:,1) == im(:,:,2)))\n is_color_image = false;\n else\n is_color_image = true;\n end\nelse\n is_color_image = false;\nend\n\nif size(im,3) > 1 && is_color_image == false\n im = im(:,:,1);\nend\n\n% Calculate search area and initial scale factor\nsearch_area = prod(init_target_sz * params.search_area_scale);\nif search_area > params.max_image_sample_size\n currentScaleFactor = sqrt(search_area / params.max_image_sample_size);\nelseif search_area < params.min_image_sample_size\n currentScaleFactor = sqrt(search_area / params.min_image_sample_size);\nelse\n currentScaleFactor = 1.0;\nend\n\n% target size at the initial scale\nbase_target_sz = target_sz / currentScaleFactor;\n\n% window size, taking padding into account\nswitch params.search_area_shape\n case 'proportional'\n img_sample_sz = floor(base_target_sz * params.search_area_scale); % proportional area, same aspect ratio as the target\n case 'square'\n img_sample_sz = repmat(sqrt(prod(base_target_sz * params.search_area_scale)), 1, 2); % square area, ignores the target aspect ratio\n case 'fix_padding'\n img_sample_sz = base_target_sz + sqrt(prod(base_target_sz * params.search_area_scale) + (base_target_sz(1) - base_target_sz(2))/4) - sum(base_target_sz)/2; % const padding\n case 'custom'\n img_sample_sz = [base_target_sz(1)*2 base_target_sz(2)*2];\nend\n\n[features, global_fparams, feature_info] = init_features(features, global_fparams, is_color_image, img_sample_sz, 'exact');\n\n% Set feature info\nimg_support_sz = feature_info.img_support_sz;\nfeature_sz = unique(feature_info.data_sz, 'rows', 'stable');\nfeature_cell_sz = unique(feature_info.min_cell_size, 'rows', 'stable');\nnum_feature_blocks = size(feature_sz, 1);\nfeature_extract_info = get_feature_extract_info(features);\n\n% Size of the extracted feature maps\nfeature_sz_cell = mat2cell(feature_sz, ones(1,num_feature_blocks), 2);\nfilter_sz = feature_sz;\nfilter_sz_cell = permute(mat2cell(filter_sz, ones(1,num_feature_blocks), 2), [2 3 1]);\n\n% The size of the label function DFT. Equal to the maximum filter size\n[output_sz, k1] = max(filter_sz, [], 1);\nk1 = k1(1);\n\n% Get the remaining block indices\nblock_inds = 1:num_feature_blocks;\nblock_inds(k1) = [];\n\n% Construct the Gaussian label function\nyf = cell(numel(num_feature_blocks), 1);\nfor i = 1:num_feature_blocks\n sz = filter_sz_cell{i};\n output_sigma = sqrt(prod(floor(base_target_sz/feature_cell_sz(i)))) * params.output_sigma_factor;\n rg = circshift(-floor((sz(1)-1)/2):ceil((sz(1)-1)/2), [0 -floor((sz(1)-1)/2)]);\n cg = circshift(-floor((sz(2)-1)/2):ceil((sz(2)-1)/2), [0 -floor((sz(2)-1)/2)]);\n [rs, cs] = ndgrid(rg,cg);\n y = exp(-0.5 * (((rs.^2 + cs.^2) / output_sigma^2)));\n yf{i} = fft2(y); \nend\n\n% Compute the cosine windows\ncos_window = cellfun(@(sz) hann(sz(1))*hann(sz(2))', feature_sz_cell, 'uniformoutput', false);\n\n% Define spatial regularization windows\nreg_window = cell(num_feature_blocks, 1);\nfor i = 1:num_feature_blocks\n reg_scale = floor(1.3*base_target_sz/params.feature_downsample_ratio(i));\n use_sz = filter_sz_cell{i}; \n reg_window{i} = ones(use_sz) * 1e5;\n range = zeros(numel(reg_scale), 2);\n \n % determine the target center and range in the regularization windows\n for j = 1:numel(reg_scale)\n range(j,:) = [0, reg_scale(j) - 1] - floor(reg_scale(j) / 2);\n end\n center = floor((use_sz + 1)/ 2) + mod(use_sz + 1,2);\n range_h = (center(1)+ range(1,1)) : (center(1) + range(1,2));\n range_w = (center(2)+ range(2,1)) : (center(2) + range(2,2));\n \n reg_window{i}(range_h, range_w) = 1e-3;\nend\nparams.reg_window = reg_window;\n\n% Pre-computes the grid that is used for socre optimization\nky = circshift(-floor((filter_sz_cell{1}(1) - 1)/2) : ceil((filter_sz_cell{1}(1) - 1)/2), [1, -floor((filter_sz_cell{1}(1) - 1)/2)]);\nkx = circshift(-floor((filter_sz_cell{1}(2) - 1)/2) : ceil((filter_sz_cell{1}(2) - 1)/2), [1, -floor((filter_sz_cell{1}(2) - 1)/2)])';\nnewton_iterations = params.newton_iterations;\n\n% Use the translation filter to estimate the scale\nnScales = params.number_of_scales;\nscale_step = params.scale_step;\nscale_exp = (-floor((nScales-1)/2):ceil((nScales-1)/2));\nscaleFactors = scale_step .^ scale_exp;\n\nif nScales > 0\n min_scale_factor = scale_step ^ ceil(log(max(5 ./ img_support_sz)) / log(scale_step));\n max_scale_factor = scale_step ^ floor(log(min([size(im,1) size(im,2)] ./ base_target_sz)) / log(scale_step));\nend\n\nseq.time = 0;\n\n% Define the learning variables\ntheta_pre_f = cell(num_feature_blocks, 1);\nctheta_f = cell(num_feature_blocks, 1);\nL = cell(num_feature_blocks, 1);\nscores_fs_feat = cell(1,1,num_feature_blocks);\nwhile true\n % Read image\n if seq.frame > 0\n [seq, im] = get_sequence_frame(seq);\n if isempty(im)\n break;\n end\n if size(im,3) > 1 && is_color_image == false\n im = im(:,:,1);\n end\n else\n seq.frame = 1;\n end\n\n tic();\n \n %% Target localization stage\n \n if seq.frame > 1\n old_pos = inf(size(pos));\n iter = 1;\n \n %translation search\n while iter <= params.refinement_iterations && any(old_pos ~= pos)\n % Extract features at multiple resolutions\n sample_pos = round(pos);\n det_sample_pos = sample_pos;\n sample_scale = currentScaleFactor*scaleFactors;\n xt = extract_features(im, sample_pos, sample_scale, features, global_fparams, feature_extract_info);\n \n % Do windowing of features\n xtw = cellfun(@(feat_map, cos_window) bsxfun(@times, feat_map, sqrt(cos_window)), xt, cos_window, 'uniformoutput', false);\n \n % Compute the fourier series\n xtf = cellfun(@fft2, xtw, 'uniformoutput', false);\n \n scores_fs_feat{k1} = gather(sum(bsxfun(@times, conj(ctheta_f{k1}), xtf{k1}), 3));\n scores_fs_sum = scores_fs_feat{k1};\n for k = block_inds\n scores_fs_feat{k} = gather(sum(bsxfun(@times, conj(ctheta_f{k}), xtf{k}), 3));\n scores_fs_feat{k} = resizeDFT2(scores_fs_feat{k}, output_sz);\n scores_fs_sum = scores_fs_sum + scores_fs_feat{k};\n end\n scores_fs = permute(gather(scores_fs_sum), [1 2 4 3]);\n \n responsef_padded = resizeDFT2(scores_fs, output_sz);\n response = ifft2(responsef_padded, 'symmetric');\n [disp_row, disp_col, sind] = resp_newton(response, responsef_padded, newton_iterations, ky, kx, output_sz);\n \n % Compute the translation vector in pixel-coordinates and round\n % to the closest integer pixel.\n translation_vec = [disp_row, disp_col] .* (img_support_sz./output_sz) * currentScaleFactor * scaleFactors(sind); \n scale_change_factor = scaleFactors(sind);\n \n % update position\n old_pos = pos;\n if sum(isnan(translation_vec))\n pos = sample_pos;\n else\n pos = sample_pos + translation_vec;\n end\n \n if params.clamp_position\n pos = max([1 1], min([size(im,1) size(im,2)], pos));\n end\n \n % Update the scale\n currentScaleFactor = currentScaleFactor * scale_change_factor;\n \n % Adjust to make sure we are not to large or to small\n if currentScaleFactor < min_scale_factor\n currentScaleFactor = min_scale_factor;\n elseif currentScaleFactor > max_scale_factor\n currentScaleFactor = max_scale_factor;\n end\n \n iter = iter + 1;\n end\n end\n \n %% Model learning and update stage\n \n % extract image region for training sample\n sample_pos = round(pos);\n xl = extract_features(im, sample_pos, currentScaleFactor, features, global_fparams, feature_extract_info);\n\n % do windowing of features\n xlw = cellfun(@(feat_map, cos_window) bsxfun(@times, feat_map, cos_window), xl, cos_window, 'uniformoutput', false);\n\n % compute the fourier series\n xlf = cellfun(@fft2, xlw, 'uniformoutput', false); \n\n [ctheta_f, theta_pre_f, L] = train_filter(ctheta_f, xlf, yf, theta_pre_f, params, output_sz, seq);\n \n % Update target size \n target_sz = base_target_sz * currentScaleFactor;\n \n % save position and time\n tracking_result.center_pos = double(pos);\n tracking_result.target_size = double(target_sz);\n seq = report_tracking_result(seq, tracking_result);\n \n seq.time = seq.time + toc();\n \n\n %% Visualization\n \n if params.visualization\n rect_position_vis = [pos([2,1]) - (target_sz([2,1]) - 1)/2, target_sz([2,1])];\n im_to_show = double(im)/255;\n if size(im_to_show,3) == 1\n im_to_show = repmat(im_to_show, [1 1 3]);\n end\n if seq.frame == 1 \n fig_handle = figure('Name', 'Tracking');\n imagesc(im_to_show);\n hold on;\n rectangle('Position',rect_position_vis, 'EdgeColor','g', 'LineWidth',2);\n text(10, 10, int2str(seq.frame), 'color', [0 1 1]);\n hold off;\n axis off;axis image;set(gca, 'Units', 'normalized', 'Position', [0 0 1 1])\n \n else\n % Do visualization of the sampled confidence scores overlayed\n% resp_sz = round(img_support_sz*currentScaleFactor*scaleFactors(sind));\n% xs = floor(det_sample_pos(2)) + (1:resp_sz(2)) - floor(resp_sz(2)/2);\n% ys = floor(det_sample_pos(1)) + (1:resp_sz(1)) - floor(resp_sz(1)/2);\n% spatial_feature_display = circshift(imresize(L{1},[numel(xs),numel(ys)]);\n figure(fig_handle);\n imagesc(im_to_show);\n% hold on;\n% resp_handle = imagesc(xs, ys, spatial_feature_display); colormap hsv;\n% alpha(resp_handle, 0.5);\n rectangle('Position',rect_position_vis, 'EdgeColor','g', 'LineWidth',2);\n text(10, 10, int2str(seq.frame), 'color', [0 1 1]);\n hold off;\n \n end\n \n drawnow\n\n end\n\nend\n\n[seq, results] = get_sequence_results(seq);\n\n", "meta": {"author": "XU-TIANYANG", "repo": "LADCF", "sha": "73258b5d3a0c8ea91e416b3afb2466fbead8bf90", "save_path": "github-repos/MATLAB/XU-TIANYANG-LADCF", "path": "github-repos/MATLAB/XU-TIANYANG-LADCF/LADCF-73258b5d3a0c8ea91e416b3afb2466fbead8bf90/tracker_imple/tracker.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.39814003004298887}}
{"text": "function test_suite = test_intersectPlaneSphere\n%TESTINTERSECTPLANESPHERE One-line description here, please.\n%\n% output = testIntersectPlaneSphere(input)\n%\n% Example\n% testIntersectPlaneSphere\n%\n% See also\n%\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2011-06-21, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2011 INRA - Cepia Software Platform.\n\ntest_suite = functiontests(localfunctions); \n\nfunction testOx(testCase) %#ok<*DEFNU>\n% Plane normal to direction [1 0 0]\n\ncenter = [10 20 30];\nradius = 50;\nsphere = [center radius];\n\nplane = createPlane(center, [6 0 0]);\n\ncircle = intersectPlaneSphere(plane, sphere);\n\nexp = [center radius 90 0 0];\ntestCase.assertEqual(exp, circle);\n\n\nfunction testOxShifted(testCase)\n% Plane normal to direction [1 0 0]\n\ncenter = [10 20 30];\nradius = 50;\nsphere = [center radius];\n\ncenter2 = center + [radius/2 0 0];\nplane = createPlane(center2, [6 0 0]);\n\ncircle = intersectPlaneSphere(plane, sphere);\n\nradius2 = radius * sqrt(3) / 2;\nexp = [center2 radius2 90 0 0];\ntestCase.assertEqual(exp, circle);\n\n\nfunction testOy(testCase)\n% Plane normal to direction [0 1 0]\n\ncenter = [10 20 30];\nradius = 50;\nsphere = [center radius];\n\nplane = createPlane(center, [0 6 0]);\n\ncircle = intersectPlaneSphere(plane, sphere);\n\nexp = [center radius 90 90 0];\ntestCase.assertEqual(exp, circle, 'AbsTol', .01);\n\n\nfunction testOyShifted(testCase)\n% Plane normal to direction [0 1 0]\n\ncenter = [10 20 30];\nradius = 50;\nsphere = [center radius];\n\ncenter2 = center + [0 radius/2 0];\nplane = createPlane(center2, [0 6 0]);\n\ncircle = intersectPlaneSphere(plane, sphere);\n\nradius2 = radius * sqrt(3) / 2;\nexp = [center2 radius2 90 90 0];\ntestCase.assertEqual(exp, circle, 'AbsTol', .01);\n\n\nfunction testOz(testCase)\n% Plane normal to direction [0 1 0]\n\ncenter = [10 20 30];\nradius = 50;\nsphere = [center radius];\n\nplane = createPlane(center, [0 0 6]);\n\ncircle = intersectPlaneSphere(plane, sphere);\n\nexp = [center radius 0 0 0];\ntestCase.assertEqual(exp, circle, 'AbsTol', .01);\n\n\nfunction testOzShifted(testCase)\n% Plane normal to direction [0 0 1]\n\ncenter = [10 20 30];\nradius = 50;\nsphere = [center radius];\n\ncenter2 = center + [0 0 radius/2];\nplane = createPlane(center2, [0 0 6]);\n\ncircle = intersectPlaneSphere(plane, sphere);\n\nradius2 = radius * sqrt(3) / 2;\nexp = [center2 radius2 0 0 0];\ntestCase.assertEqual(exp, circle, 'AbsTol', .01);\n\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/tests/geom3d/test_intersectPlaneSphere.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.3981400272029898}}
{"text": "function output = calloptiqsopt(interfacedata)\n\n% Standard input interface\noptions = interfacedata.options;\nF_struc = interfacedata.F_struc;\nc = interfacedata.c;\nK = interfacedata.K;\nlb = interfacedata.lb;\nub = interfacedata.ub;\n\nshowprogress('Calling QSOPT',options.showprogress);\n\nif isempty(F_struc) \n A = [];\n b = [];\nelse\n A =[-F_struc(K.f+1:end,2:end);-F_struc(1:K.f,2:end)];\n b =[F_struc(K.f+1:end,1);F_struc(1:K.f,1)]; \nend\n\nopts = options.qsopt;\nopts.nin = length(b)-K.f;\nopts.display = options.verbose;\n\nif options.savedebug \n save qsoptdebug c A b lb ub opts\nend\n\nsolvertime = tic;\n[x,fval,exitflag] = qsopt(full(c), A, full(b), full(lb), full(ub),opts);\nsolvertime = toc(solvertime);\n\n% No duals\nD_struc = [];\n\nswitch exitflag\n case 1\n problem = 0;\n case 0\n problem = 3;\n case -1\n problem = 1;\n case -2\n problem = 11; \n otherwise\n problem = -1;\nend\ninfostr = yalmiperror(problem,'QSOPT'); \n\n% Save all data sent to solver?\nif options.savesolverinput\n solverinput.A = A;\n solverinput.b = b;\n solverinput.f = c;\n solverinput.lb = lb;\n solverinput.ub = ub; \nelse\n solverinput = [];\nend\n\n% Save all data from the solver?\nif options.savesolveroutput\n solveroutput.x = x;\n solveroutput.fval = fval;\n solveroutput.exitflag = exitflag;\nelse\n solveroutput = [];\nend\n\n% Standard interface \noutput = createOutputStructure(x,D_struc,[],problem,infostr,solverinput,solveroutput,solvertime);", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/YALMIP/solvers/calloptiqsopt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255927, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.39814002436299056}}
{"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": "clear;\naddpath('../../CVPR16_VDSR/');\naddpath('./matlabPyrTools-master/');\n%% test\n% load('DRRN_22C128_dataset_1_x3');\nload('VDSR_20C64_dataset_1_x3');\npath = ['../../SR Test dataset/Set5/'];\nd = dir([path '*.bmp']);\nup_scale = 3;\nsum = 0 ;\nfor i=1:length(d)\n im = imread([path d(i).name]);\n %% work on illuminance only\n if size(im,3)>1\n im = rgb2ycbcr(im);\n end\n im = im2double(im(:,:,1));\n im_gnd = modcrop(im, up_scale);\n [hei,wid] = size(im_gnd);\n im_b = imresize(imresize(im_gnd,1/up_scale,'bicubic'),up_scale,'bicubic');\n %% remove border\n im_b1 = shave(uint8(single(im_b) * 255), [up_scale, up_scale]);\n im_gnd1 = shave(uint8(single(im_gnd) * 255), [up_scale, up_scale]);\n im_h1 = im_h_set{i};\n sum = sum+ifcvec(double(im_gnd1),double(im_h1));\nend\nifc = sum/length(d)\n\n\n ", "meta": {"author": "tyshiwo", "repo": "DRRN_CVPR17", "sha": "cafe98bc73997c10947911de74279d63cb786b8a", "save_path": "github-repos/MATLAB/tyshiwo-DRRN_CVPR17", "path": "github-repos/MATLAB/tyshiwo-DRRN_CVPR17/DRRN_CVPR17-cafe98bc73997c10947911de74279d63cb786b8a/test/evaluation_func/demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3981058864595031}}
{"text": "function [costPatchCand, uvBiasCand] = ...\n sc_patch_cost(trgPatch, srcPatch, modelPlane, uvPlaneIDData, ...\n trgPos, srcTform, srcPosMap, bdPos, optS)\n\nnumUvPix = size(srcPatch, 3);\ncostPatchCand = zeros(numUvPix, 4, 'single');\n\n% Patch cost - appearance\n[costApp, uvBiasCand] = sc_patch_cost_app(trgPatch, srcPatch, optS);\n\n% Patch cost - planar guidance\nsrcPos = srcTform(:,7:8);\ncostPlane = sc_patch_cost_plane(modelPlane.mLogLPlaneProb, uvPlaneIDData, trgPos, srcPos);\n\nif(optS.useCoherence) % Patch cost - coherence\n costCoherence = sc_patch_cost_coherence(trgPos, srcPosMap, srcTform, optS);\nend\n\n% Patch cost - directional guidance\ncostDirect = sc_patch_cost_direct(uvPlaneIDData, trgPos, srcPos, modelPlane, optS);\n\n% Patch cost - proximity cost\ncostProx = sc_patch_cost_prox(srcPos, trgPos, bdPos, optS);\n\n% costReg = double(uvPixUpdateSrc == 1);\n\n% Weighted sum of the appearance cost and guidance cost\ncostPatchCand(:,1) = costApp;\ncostPatchCand(:,2) = optS.lambdaPlane * costPlane;\n\nif(optS.useCoherence)\n costPatchCand(:,3) = optS.lambdaCoherence * costCoherence;\nend\n\ncostPatchCand(:,4) = optS.lambdaDirect * costDirect;\ncostPatchCand(:,5) = optS.lambdaProx * costProx;\n% costPatchCand(3,:) = optS.lambdaReg * costReg;\n\n% [To-Do] Adaptive weighting for patch cost\n% costPatchCand(2:5,:) = (iLvl/optS.numPyrLvl)*costPatchCand(2:5,:);\n\nend\n\nfunction [costApp, uvBias] = sc_patch_cost_app(trgPatch, srcPatch, optS)\n\n% SC_PATCH_COST_APP\n%\n% Compute the weighted sum of the absolute difference between\n% cost between source and target patches\n\n% Input:\n% - trgPatch: target patch\n% - srcPatch: source patch\n% - optS: parameter\n% Output:\n% - costApp: appearance cost\n% - uvBias bias for the closet neighbor\n\n% =========================================================================\n% Apply bias correction\n% =========================================================================\n\nuvBias = [];\nif(optS.useBiasCorrection)\n % Mean of source and target patch\n meanTrgPatch = mean(trgPatch, 1);\n meanSrcPatch = mean(srcPatch, 1);\n \n % Compute bias and clamp it to inteval [optS.minBias, optS.maxBias]\n uvBias = meanTrgPatch - meanSrcPatch;\n uvBias = sc_clamp(uvBias, optS.minBias, optS.maxBias);\n \n % Update the UV map for bias\n % uvBias = reshape(biasPatch, 3, numUvValidPix);\n \n % Apply the bias correction to source patch\n srcPatch = bsxfun(@plus, srcPatch, uvBias);\nend\n\n% =========================================================================\n% Compute weighted distance\n% =========================================================================\n% Compute distance\npatchDist = trgPatch - srcPatch;\n\n% Sum of absolute distance\nif(strcmp(optS.costType, 'L1'))\n patchDist = abs(patchDist);\nelseif(strcmp(optS.costType, 'L2'))\n patchDist = patchDist.^2;\nend\n\n% Apply weights\npatchDist = bsxfun(@times, patchDist, optS.wPatch);\ncostApp = squeeze(sum(sum(patchDist, 1),2));\nend\n\nfunction cost = sc_patch_cost_coherence(trgPos, srcPosMap, srcTform, opt)\n\n% SC_PATCH_COST_COHERENCE: spatial coherence cost\n%\n% Input\n% - trgPos: target patch positions [numPix] x [2]\n% - srcPosMap: source patch map [imgH] x [imgW] x [2]\n% - srcPos: source patch positions [numPix] x [2]\n% - srcTfmG: source patch geometric transformation [numPix] x [9]\n% - opt: parameters\n% Output:\n% - cost: spatio-temporal coherence cost\n\nnumPix = size(trgPos,1);\n[imgH, imgW, ~] = size(srcPosMap);\n\n% initialize coherence cost\ncost = zeros(numPix, 1, 'single');\n\n% =========================================================================\n% Compute spatial coherence cost\n% =========================================================================\nfor i = 1:4\n % source patch position prediction\n v = opt.propDir(i,:);\n srcPosP = sc_trans_tform(srcTform, v);\n srcPosP = srcPosP(:,7:8);\n \n % source patch positions of neighboring target patches\n trgPosN = bsxfun(@plus, trgPos, v);\n trgIndN = uint32(sub2ind([imgH, imgW], trgPosN(:,2), trgPosN(:,1)));\n srcPosN = sc_uvMat_from_uvMap(srcPosMap, trgIndN);\n \n validSrc = (srcPosN(:,1) ~= 0);\n \n % add cost if the differences are high\n diff = zeros(numPix, 1, 'single');\n diff(validSrc) = sum(abs(srcPosP(validSrc,:) - srcPosN(validSrc,:)), 2) > 1;\n cost = cost + diff;\nend\n\n% cost = opt.lambdaCoherence*cost;\n\nend\n\nfunction costPlane = sc_patch_cost_plane(mLogLPlaneProb, uvPlaneIDData, trgPixSub, srcPixSub)\n\n% SC_PATCH_COST_PLANE\n%\n% Compute planar costs (See Eqn 11 in the paper)\n\n[imgH, imgW, numPlane] = size(mLogLPlaneProb);\n\nsrcPixSub = round(srcPixSub);\nuvPlaneIDData = double(uvPlaneIDData);\n\ntrgPixIndCur = sub2ind([imgH, imgW, numPlane], trgPixSub(:,2), trgPixSub(:,1), uvPlaneIDData);\nsrcPixIndCur = sub2ind([imgH, imgW, numPlane], srcPixSub(:,2), srcPixSub(:,1), uvPlaneIDData);\n\ncostPlane = mLogLPlaneProb(trgPixIndCur) + mLogLPlaneProb(srcPixIndCur);\n\nend\n\nfunction costProx = sc_patch_cost_prox(srcPos, trgPos, uvDtBdPixPos, optS)\n\n% SC_PATCH_COST_PROX\n\n% Encourage to sample patches near to the target patch\n\nd = srcPos - trgPos;\nd = sqrt(sum(d.^2,2));\n\nd = d/optS.imgSize;\nuvDtBdPixPos = uvDtBdPixPos/optS.imgSize;\n\n% costProx = max(0, d - optS.proxThres);\n% Shrinkage thresholding\ncostProx = max(0, d - uvDtBdPixPos - optS.proxThres);\n% costProx = max(0, d - optS.proxThres);\n\nend\n\n\nfunction costDirect = sc_patch_cost_direct(uvPlaneIDData, trgPos, srcPos, modelPlane, optS)\n\n% SC_PATCH_COST_DIRECT\n%\n% Compute the directional cost (See Eqn 13 in the paper)\n%\n% Input\n% -\n% Output\n% -\n\nnumUvPix = size(trgPos, 1);\ncostDirect = optS.lambdaDirect*ones(numUvPix, 2, 'single');\n\nfor indPlane = 1: modelPlane.numPlane\n % Retrieve the uv pixels that have the current plane label\n uvPlaneIndCur = uvPlaneIDData == indPlane;\n numPlanePixCur = sum(uvPlaneIndCur);\n \n if(indPlane == modelPlane.numPlane)\n costDirect(uvPlaneIndCur, :) = optS.imgSize*optS.directThres;\n else\n % The rectifying transformation for the plane\n rectMat = modelPlane.rectMat{indPlane};\n h7 = rectMat(3,1);\n h8 = rectMat(3,2);\n \n if(numPlanePixCur~=0)\n trgPosCur = trgPos(uvPlaneIndCur, :) - 1;\n srcPosCur = srcPos(uvPlaneIndCur, :) - 1;\n \n for iTheta = 1:2\n rotMat = modelPlane.rotMat{indPlane, iTheta};\n \n rotRecMat = rotMat;\n rotRecMat(3,1) = h7; rotRecMat(3,2) = h8;\n rotRecMat = rotRecMat';\n \n trgPosCurRect = cat(2, trgPosCur, ones(numPlanePixCur,1))*rotRecMat;\n trgPosCurRect = bsxfun(@rdivide, trgPosCurRect, trgPosCurRect(:,3));\n \n % Source patch center position in the rectified domain\n srcPosCurRect = cat(2, srcPosCur, ones(numPlanePixCur,1))*rotRecMat;\n srcPosCurRect = bsxfun(@rdivide, srcPosCurRect, srcPosCurRect(:,3));\n \n costDirect(uvPlaneIndCur, iTheta) = abs(srcPosCurRect(:,2) - trgPosCurRect(:,2));\n end\n end\n end\nend\n\ncostDirect = min(costDirect, [], 2);\ncostDirect = min(costDirect/optS.imgSize, optS.directThres);\n\nend", "meta": {"author": "jbhuang0604", "repo": "StructCompletion", "sha": "25668dea193801140fafe0a722ccb1e955509ec4", "save_path": "github-repos/MATLAB/jbhuang0604-StructCompletion", "path": "github-repos/MATLAB/jbhuang0604-StructCompletion/StructCompletion-25668dea193801140fafe0a722ccb1e955509ec4/source/sc_patch_cost.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3981058864595031}}
{"text": "filename='RVE_Square_Triangle_FineFine';\nptype = 'MICRO';\nmethod = 'SIMPALL';\nmaterialType = 'ISOTROPIC';\ninitial_case = 'horizontal';\ncost={'chomog_alphabeta'};\nweights=[1 0.1];\nconstraint = {'volumeConstraint'};\noptimizer = 'SLERP'; \nincrementFactor = 1;\ndesignVariable = 'LevelSet';\nfilterType = 'P1';\n\nnsteps = 1;\nVfrac_final = 0.5;\nPerimeter_target=1;\noptimality_final =1e-3;\nconstr_final =1e-3;\n\nVfrac_initial = 1;\noptimality_initial = 1e-3;\nconstr_initial = 1e-3;\n\nTOL.rho_plus = 1;\nTOL.rho_minus = 0;\nTOL.E_plus = 1;\nTOL.E_minus = 1e-3;\nTOL.nu_plus = 1/3;\nTOL.nu_minus = 1/3;\n\n%Micro\nepsilon_isotropy_initial=1e-1;\nepsilon_isotropy_final = 1e-3;\nmicro.alpha =[1 1 0]';\nmicro.beta =[1 1 0]';\n\n% For all tests\nplotting = false;\nprinting = false;\nmonitoring = false;\nmaxiter = 3;\n", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/Input/test_microHorizontalFine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3980791521373911}}
{"text": "function [acc_stl] = STL(X_src,y_src,X_tar,y_tar,dim)\n% Stratified Transfer Learning for Cross-domain Activity Recognition.\n% Jindong Wang, Yiqiang Chen, Lisha hu, Xiaohui Peng, and Philip S. Yu.\n% 2018 IEEE International Conference on Pervasive Computing and Communications (PerCom).\n\n%% Inputs: \n%%%% X_src : Source domain feature matrix, n_sample * n_dim\n%%%% y_src : Source domain label vector, n_sample * 1\n%%%% X_tar : Target domain feature matrix, n_sample * n_dim\n%%%% y_src : Target domain label vector, n_sample * 1\n%%%% dim : Dimension after STL, an integer\n%% Output:\n%%%% acc_stl: accuracy of the algorithm\n\n label_set = unique(y_src(:));\n num_tree = 30;\n %voting\n %%RF\n [predict_label_rf,accuracy_rf] = jdrf(X_src,y_src,X_tar,y_tar,30);\n %%SVM\n [predict_label_svm,accuracy_svm,~] = jdsvm(X_src,y_src,X_tar,y_tar,100);\n %%KNN\n [predict_label_knn,accuracy_knn] = jdknn(X_src,y_src,X_tar,y_tar,5);\n %%voting\n label_voting = [];\n for i = 1 : size(y_tar,1)\n if predict_label_rf(i) == predict_label_svm(i)\n label_voting(i) = predict_label_rf(i);\n elseif predict_label_rf(i) == predict_label_knn(i)\n label_voting(i) = predict_label_rf(i);\n elseif predict_label_svm(i) == predict_label_knn(i)\n label_voting(i) = predict_label_svm(i);\n else\n label_voting(i) = -1;\n end\n end\n label_voting = label_voting';\n %get residual\n r_index = label_voting(:,1) == -1;\n X_tar_residual = X_tar(r_index,:);\n y_tar_residual = y_tar(r_index,:);\n \n %get candidate\n c_index = label_voting(:,1) ~= -1;\n X_tar_candidate = X_tar(c_index,:);\n y_tar_candidate = y_tar(c_index,:);\n label_candidate = label_voting(c_index);\n conmat1 = confusionmat(label_candidate,y_tar_candidate);\n %in-class transfer\n %%%new candidates and source domain\n X_tar_candidate_new = [];\n y_tar_candidate_new = [];\n X_src_new = [];\n y_src_new = [];\n X_tar_candidate_old = [];\n y_tar_candidate_old = [];\n for i = 1 : size(label_set,1)\n class_index = label_set(i);\n %source data in that class i\n src_index_i = y_src(:) == class_index;\n X_src_i = X_src(src_index_i,:);\n y_src_i = y_src(src_index_i,:);\n %candidate data in that class i\n tar_index_i = label_candidate(:) == class_index;\n X_tar_candidate_i = X_tar_candidate(tar_index_i,:);\n y_tar_candidate_i = y_tar_candidate(tar_index_i,:);\n X_tar_candidate_old = [X_tar_candidate_old;X_tar_candidate_i];\n y_tar_candidate_old = [y_tar_candidate_old;y_tar_candidate_i];\n %TCA\n [X_src_new_i,X_tar_candidate_new_i] = MyTCA(X_src_i,X_tar_candidate_i,dim);\n %merge\n X_src_new = [X_src_new;X_src_new_i];\n y_src_new = [y_src_new;y_src_i];\n X_tar_candidate_new = [X_tar_candidate_new;X_tar_candidate_new_i];\n y_tar_candidate_new = [y_tar_candidate_new;y_tar_candidate_i];\n end\n %train model on new candidate\n [predicted_label_candidate,acc_candidate] = ...\n jdrf(X_src_new,y_src_new,X_tar_candidate_new,y_tar_candidate_new,num_tree);\n conmat2 = confusionmat(predicted_label_candidate,y_tar_candidate_new);\n %train model on old candidate and predict on residual\n [predicted_label_residual,acc_residual] = jdrf(X_tar_candidate_old,predicted_label_candidate,X_tar_residual,y_tar_residual,num_tree);\n %calculate accuracy\n acc_stl = mean([predicted_label_candidate;predicted_label_residual] == [y_tar_candidate_new;y_tar_residual]);\n \nend", "meta": {"author": "jindongwang", "repo": "activityrecognition", "sha": "33687803886d4a184e0b285e3ec7ab73a8f86355", "save_path": "github-repos/MATLAB/jindongwang-activityrecognition", "path": "github-repos/MATLAB/jindongwang-activityrecognition/activityrecognition-33687803886d4a184e0b285e3ec7ab73a8f86355/code/percom18_stl/STL.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3980791463221694}}
{"text": "% op_getcoilcombos_specReg.m\n% Jamie Near, McGill University 2014.\n% \n% USAGE:\n% coilcombos=op_getcoilcombos_specReg(file_or_struct,tmin,tmax,point);\n% \n% DESCRIPTION:\n% This funciton finds the relative coil phases and amplitudes. Coil phases\n% are found by fitting in the time domain. (In the original\n% op_getcoilcombos, the phases were determined simply by observation of the\n% pointth point in the time domain). The \"Base\" receiver channel is\n% Determined as the one with the highest signal (all other coil channels\n% will be registered to that channel. \n% \n% INPUTS:\n% file_or_struct = this function will accept either a string filename or\n% the name of a structure. If the input is a string, \n% the program will read in the data corresponding to \n% that filename. If the input is a structure, it will\n% operate on that structure.\n% tmin = The earliest timepoint in the fid to be used for \n% spectral registration. (Optional. Default=0 sec);\n% tmax = The latest timepoint in the fid to be used for \n% spectral registration. (Optional. Default=0.2 sec);\n% point = The index of the datapoint in the fid that is used\n% for determination of Signal intensity. (Optional.\n% Default = 1);\n%\n% OUTPUTS:\n% coilcombos = Structure containing the calculated coil weights and phases. \n\n\nfunction coilcombos=op_getcoilcombos_specReg(file_or_struct,tmin,tmax,point);\n\n\nif isstr(file_or_struct)\n in=io_loadspec_twix(file_or_struct);\nelse\n in=file_or_struct;\nend\n\nif in.flags.addedrcvrs || ~in.dims.coils\n %If there is only one coil element, do nothing:\n disp('WARNING: Only one receiver channel found! Coil phase will be 0.0 and coil amplitude will be 1.0.');\n coilcombos.ph=0;\n coilcombos.sig=1;\nelse\n %If there are multiple coil elements (most cases), find the complex\n %weightings\n\n if nargin<4\n point=1;\n if nargin<3\n tmax=0.2;\n if nargin<2\n tmin=0;\n end\n end\n end\n\n B=in.sz(in.dims.coils);\n \n coilcombos.ph=zeros(B,1);\n coilcombos.sig(:,1)=abs(in.fids(point,:,1,1));\n bestSNRindex=find(coilcombos.sig(:,1)==max(coilcombos.sig(:,1)))\n phGuess=0;\n \n disp('aligning all coils to the first coil');\n base=phase(in.fids(in.t>=tmin & in.t=tmin & in.t 0,'gamma must be a positive value; see the instructions at http://www.csie.ntu.edu.tw/~cjlin/libsvm/ for more information');\n obj.gamma = val;\n end\n end\n function obj = set.coef0(obj,val)\n assert(isscalar(val),'coef0 must be a scalar; see the instructions at http://www.csie.ntu.edu.tw/~cjlin/libsvm/ for more information');\n obj.coef0 = val;\n end\n function obj = set.cost(obj,val)\n assert(isscalar(val) && val > 0,'cost must be a positive value; see the instructions at http://www.csie.ntu.edu.tw/~cjlin/libsvm/ for more information');\n obj.cost = val;\n end\n function obj = set.nu(obj,val)\n assert(isscalar(val) && val > 0,'nu must be a positive value; see the instructions at http://www.csie.ntu.edu.tw/~cjlin/libsvm/ for more information');\n obj.nu = val;\n end\n function obj = set.pEpsilon(obj,val)\n assert(isscalar(val) && val > 0,'pEpsilon must be a positive value; see the instructions at http://www.csie.ntu.edu.tw/~cjlin/libsvm/ for more information');\n obj.pEpsilon = val;\n end\n function obj = set.cachesize(obj,val)\n assert(isscalar(val) && val > 0,'cachesize must be a positive value; see the instructions at http://www.csie.ntu.edu.tw/~cjlin/libsvm/ for more information');\n obj.cachesize = val;\n end\n function obj = set.eEpsilon(obj,val)\n assert(isscalar(val) && val > 0,'eEpsilon must be a positive value; see the instructions at http://www.csie.ntu.edu.tw/~cjlin/libsvm/ for more information');\n obj.eEpsilon = val;\n end\n function obj = set.shrinking(obj,val)\n val = double(val);\n assert(isscalar(val) && ismember(val,[0 1]),'shrinking must be one of 0,1; see the instructions at http://www.csie.ntu.edu.tw/~cjlin/libsvm/ for more information');\n obj.shrinking = val;\n end\n function obj = set.probabilityEstimates(obj,val)\n val = double(val);\n assert(isscalar(val) && ismember(val,[0 1]),'probabilityEstimates must be one of 0,1; see the instructions at http://www.csie.ntu.edu.tw/~cjlin/libsvm/ for more information');\n obj.probabilityEstimates = val;\n end\n function obj = set.weight(obj,val)\n assert(numel(val)==2 && all(val > 0),'weight must be a positive 2-element vector; see the instructions at http://www.csie.ntu.edu.tw/~cjlin/libsvm/ for more information');\n obj.weight = val;\n end\n \n function self = prtClassLibSvm(varargin)\n self = prtUtilAssignStringValuePairs(self,varargin{:});\n end \n end\n \n methods (Access=protected, Hidden = true)\n \n function self = trainAction(self,dataSet)\n \n % Its ok to have 1 class if its a 1 class classifier\n if dataSet.nClasses ~= 2 && self.svmType ~=2\n error('prt:prtClassLibSvm:UnaryData','prtClassLibSvm requires binary data for training');\n end\n if dataSet.nClasses ~= 1 && self.svmType ==2\n % You can avoid this warning using\n % prtOutlierRemovalFnTargets in your algorithm spec. \n warning('prt:prtClassLibSvm:UnaryData','prtClassLibSvm requires unary data for training when svmType = 2; using max(dataSet.uniqueClasses) as the default single class.');\n dataSet = dataSet.retainClasses(max(dataSet.uniqueClasses));\n end\n \n training_label_vector = dataSet.getTargetsAsBinaryMatrix;\n training_label_vector = double(training_label_vector(:,end)); %zeros and ones\n training_instance_matrix = dataSet.getObservations;\n self.libSvmOptions = self.libSvmOptionString(dataSet);\n self.libSvmOptionsTest = self.libSvmOptionStringTest(dataSet);\n \n if self.kernelType == 4\n %self.userSpecKernel = prtKernelRbfNdimensionScale;\n if ~isa(self.userSpecKernel,'prtKernel') && ~isa(self.userSpecKernel,'function_handle')\n error('prtClassLibSvm:KernelType4','For kernelType = 4 (user-specified kernel), svm.userSpecKernel must be a prtKernel or function handle');\n end\n if isa(self.userSpecKernel,'prtKernel')\n self.userSpecKernel = self.userSpecKernel.train(dataSet);\n kernelMat = self.userSpecKernel.run(dataSet);\n training_instance_matrix = kernelMat.data;\n else\n training_instance_matrix = self.userSpecKernel(dataSet.X,dataSet.X);\n end\n training_instance_matrix = cat(2,(1:size(training_instance_matrix,1))',training_instance_matrix);\n end \n self.trainedSvm = prtExternal.libsvm.svmtrain(training_label_vector, training_instance_matrix, self.libSvmOptions);\n \n %Need to figure out whether to flip SVM outputs:\n yOut = runAction(self,dataSet);\n auc = prtScoreAuc(yOut.retainLabeled);\n \n %libSVM has some weird rules about target names. the first target type it finds is called H1...\n % We can fix this either above, or here\n if auc < .5 \n self.gain = -1;\n end\n end\n \n function DataSetOut = runAction(self,dataSet)\n\n testing_label_vector = double(dataSet.getTargets);\n if isempty(testing_label_vector)\n testing_label_vector = zeros(dataSet.nObservations,1);\n end\n \n if self.kernelType == 4\n if ~isa(self.userSpecKernel,'prtKernel') && ~isa(self.userSpecKernel,'function_handle')\n error('prtClassLibSvm:KernelType4','For kernelType = 4 (user-specified kernel), svm.userSpecKernel must be a prtKernel or function handle');\n end\n if isa(self.userSpecKernel,'prtKernel')\n kernelMat = self.userSpecKernel.run(dataSet);\n testing_instance_matrix = kernelMat.data;\n else\n %Function handle:\n testing_instance_matrix = self.userSpecKernel(dataSet.X,self.dataSet.X);\n end\n testing_instance_matrix = cat(2,(1:size(testing_instance_matrix,1))',testing_instance_matrix);\n else\n testing_instance_matrix = dataSet.getObservations;\n end\n \n [dontNeed, dontNeed, decision_values] = prtExternal.libsvm.svmpredict(testing_label_vector, testing_instance_matrix, self.trainedSvm, self.libSvmOptionsTest); %#ok\n \n DataSetOut = dataSet;\n DataSetOut = DataSetOut.setObservations(decision_values*self.gain);\n end\n \n function dataSetOut = runActionFast(self,x,ds)\n \n switch self.kernelType\n case 2\n nFeats = size(x,2);\n f = full(self.trainedSvm.SVs);\n gram = prtKernelRbf.kernelFn(f,x,sqrt(nFeats));\n yOut = ((self.trainedSvm.sv_coef'*gram)-self.trainedSvm.rho)';\n otherwise\n error('prt:prtClassLibSvm','Unsupported kernel type for runActionFast');\n end\n dataSetOut = yOut(:)*self.gain;\n end\n \n end\n methods (Hidden = true)\n \n function str = textSummary(self)\n str = sprintf('%s: \\n',class(self));\n str2 = evalc('disp(self.trainedSvm)');\n str = sprintf('%s%s',str,str2);\n end\n function optionString = libSvmOptionString(obj,dataSet)\n if isnan(obj.gamma)\n obj.gamma = 1./dataSet.nFeatures;\n end\n if ischar(obj.gamma)\n optionString = sprintf('-s %d -t %d -d %d -g %s -r %f -c %f -n %f -p %f -m %f -e %f -h %d -b %d -w0 %f -w+1 %f',...\n obj.svmType,obj.kernelType,obj.degree,obj.gamma,obj.coef0,obj.cost,obj.nu,...\n obj.pEpsilon,obj.cachesize,obj.eEpsilon,obj.shrinking,obj.probabilityEstimates,obj.weight(1),obj.weight(2));\n else\n optionString = sprintf('-s %d -t %d -d %d -g %f -r %f -c %f -n %f -p %f -m %f -e %f -h %d -b %d -w0 %f -w+1 %f',...\n obj.svmType,obj.kernelType,obj.degree,obj.gamma,obj.coef0,obj.cost,obj.nu,...\n obj.pEpsilon,obj.cachesize,obj.eEpsilon,obj.shrinking,obj.probabilityEstimates,obj.weight(1),obj.weight(2));\n end\n end\n function optionString = libSvmOptionStringTest(obj,dataSet) %#ok\n optionString = sprintf('-b %d',obj.probabilityEstimates);\n end\n end\n \n methods (Hidden)\n function str = exportSimpleText(self) %#ok\n titleText = sprintf('%% prtClassLibSvm\\n');\n svmSvText = prtUtilMatrixToText(full(self.trainedSvm.SVs),'varName','supportVectors');\n svmSvCoeffText = prtUtilMatrixToText(full(self.trainedSvm.sv_coef),'varName','svCoefficients');\n svmSigmaText = prtUtilMatrixToText(sqrt(size(self.trainedSvm.SVs,2)),'varName','sigma');\n svmRhoText = prtUtilMatrixToText(self.trainedSvm.rho,'varName','rho');\n str = sprintf('%s%s%s%s%s',titleText,svmSvText,svmSvCoeffText,svmSigmaText,svmRhoText);\n end\n end\nend\n\n", "meta": {"author": "covartech", "repo": "PRT", "sha": "4305e612af048e7dbf3d9392efc7436db125b1fc", "save_path": "github-repos/MATLAB/covartech-PRT", "path": "github-repos/MATLAB/covartech-PRT/PRT-4305e612af048e7dbf3d9392efc7436db125b1fc/class/prtClassLibSvm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.3980707988901423}}
{"text": "% colony_count.m demo script\n% Runs colony_count on example image and displays segmentation results.\n\n% Load image.\nI = imread('plate_example.jpg');\n\n% Call function.\n% Count is number of colonies, markers is the colony markers and mask is\n% the colony segmentation. Count == # of components in markers.\n\n% Optional parameter, this is the default.\n% Should encompass internal radius of Petri dish.\nradii = 115:1:130;\n\n[count,markers,mask] = colony_count(I,radii);\n\ndisp([num2str(count) ' colonies detected.']);\n\n% Overlay image with markers and mask.\nJ = rgb2gray(I);\nR = J; G = J; B = J;\nR(mask) = 255; R(markers) = 0;\nG(mask) = 0; G(markers) = 255;\nB(mask) = 0; B(markers) = 0;\nRGB = cat(3,R,G,B);\nfigure();imshow(RGB);\n\n% Overlay image with just markers.\nR = J; G = J; B = J;\nR(markers) = 0;\nG(markers) = 255;\nB(markers) = 0;\nRGB = cat(3,R,G,B);\nfigure();imshow(RGB);", "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/35943-automated-counting-of-bacterial-colonies/colony_count/colony_count_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.727975460709318, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3980119580783604}}
{"text": "function [status, results] = mrtrix_tensor_generate (in_file, out_file, b_file, verbose)\n\n%\n% Calculate diffusion tensors. \n%\n% Parameters\n% ----------\n% in_file: The name of a diffusion file in .mif format\n% out_file: The name of the resulting dti file in .mif format\n% b_file: The name of a mrtrix format gradient vector file (default: 'encoding.b')\n%\n% Returns\n% -------\n% status: whether (0) or not (1) the operation succeeded \n% results: the results of the operation in the terminal\n%\n% Notes\n% -----\n% http://www.brain.org.au/software/mrtrix/tractography/preprocess.html\n\n\nif notDefined('verbose')\n verbose = true; \nend\nif notDefined('b_file')\n b_file = 'encoding.b';\nend \n\n% This command generates tensors: \ncmd_str = sprintf('dwi2tensor %s %s -grad %s',in_file, outfile, b_file); \n\n% Send it to mrtrix: \n[status,results] = mrtrix_cmd(cmd_str,verbose); ", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/external/mrtrix/mrtrix_tensor_generate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.39801195162502384}}
{"text": "\n\n%h = guidata(6);\nh = guidata(gcf);\nfg = h.fiberGroups(h.curFiberGroup);\n% interp method can be 'nearest'|'trilin'|'spline'. If you are going to\n% just average a bunch of these values, it's probably best to use nearest. \ninterp = 'nearest'; \nmd = dtiGetValFromFibers(h.dt6, fg, inv(dtiGet(h,'dt6xform')),'md',interp);\nfa = dtiGetValFromFibers(h.dt6, fg, inv(dtiGet(h,'dt6xform')),'fa',interp);\nln = dtiGetValFromFibers(h.dt6, fg, inv(dtiGet(h,'dt6xform')),'linearity',interp);\n\n%alignSlice = [nan -55 nan]; % the alignment position (in mm from AC)\nalignSlice = [nan nan 28]; % the alignment position (in mm from AC)\nax = find(~isnan(alignSlice));\nsl = alignSlice(ax);\nif(length(ax)~=1) error('specify just one alignment axis!'); end\nif(ax==1) axName='LR'; elseif(ax==2) axName='AP'; else axName='SI'; end\nnPts = 20;\nnFibers = length(fg.fibers);\nfiberFa = zeros(nFibers, nPts*2+1)*nan;\nfiberMd = fiberFa; fiberLn = fiberFa;\nfiberCoords = zeros(nFibers, nPts*2+1,3)*nan;\nfor(ii=1:length(fg.fibers))\n d = abs(fg.fibers{ii}(ax,:)-alignSlice(ax));\n nearInd = find(d==min(d));\n if(nearInd-nPts<=1 | nearInd+nPts>=length(fg.fibers{ii}))\n continue;\n end\n fDir = fg.fibers{ii}(ax,[nearInd-1,nearInd+1]);\n inds = [nearInd-nPts:nearInd+nPts];\n % We skip the fiber end-points, since the FA there can be misleading\n if(fDir(2)1 & inds1 & inds0\n imout = [imout; zeros(1,size(imout,2))];\nend\nif sizedif(2)>0\n imout = [imout, zeros(size(imout,1),1)];\nend", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/image_proc/padimage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.3979554069565919}}
{"text": "function f=fun1(p)\nf=1.0/(p^2);\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/9987-gaver-stehfest-algorithm-for-inverse-laplace-transform/gavsteh/fun1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.3979554069565919}}
{"text": "function rgb = oklab2rgb(ok)\n % OKLAB2RGB Convert colors stored in OKLab color space to RGB color space\n %\n % rgb = oklab2rgb(ok)\n %\n % Inputs:\n % ok #h by #w by 3 image of colors or #ok by 3 list of colors\n % Outputs:\n % rgb converted ok colors (same size as ok)\n %\n % See also: rgb2lin, lin2rgb, oklab2lin , rgb2oklab, lin2oklab\n lin = oklab2lin(ok);\n rgb = lin2rgb(lin);\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/imageprocessing/oklab2rgb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.39795042849777773}}
{"text": "function varargout = biharm(varargin)\n%BIHARM Biharmonic operator of a CHEBFUN2.\n% B = BIHARM(F) returns a CHEBFUN2 representing the biharmonic operator \n% applied to F.\n%\n% This is shorthand for BIHARMONIC(F).\n%\n% See also CHEBFUN2/BIHARMONIC.\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 SEPARABLEAPPROX/BIHARM:\n[varargout{1:nargout}] = biharm@separableApprox(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/@chebfun2/biharm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.39795042849777773}}
{"text": "function PD = pwrDiagramPD(T, PC)\n% function PD = pwrDiagramPD(T, PC)\n%\n% T: triangulation\n% PC: power centers of triangles in T\n%\n% The output cell PD contains pieces of the power diagram, indexed by\n% dimension. PD{mP} contains pieces of dimension zero (power centers that\n% correspond to fully-dimensional pieces of the triangulation T) and PD{1}\n% contains fully-dimensional regions of the power diagram (corresponding to\n% vertices of the triangulation).\n\nP = piecesPD(T);\nmP = size(P,1);\nPD = cell(mP,1);\n\nfor i=1:mP\n EA = edgeAttPD(T, P{i});\n for j=1:size(EA,1);\n EA{j} = PC(EA{j},:);\n end\n PD{i} = EA;\nend", "meta": {"author": "optimaltransport", "repo": "optimaltransport.github.io", "sha": "2fa6db6e6a48ab9bd6676088db00bd7c5c8b4203", "save_path": "github-repos/MATLAB/optimaltransport-optimaltransport.github.io", "path": "github-repos/MATLAB/optimaltransport-optimaltransport.github.io/optimaltransport.github.io-2fa6db6e6a48ab9bd6676088db00bd7c5c8b4203/_site/code/semi-discrete/power_diagrams/pwrDiagramPD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.39795042849777773}}
{"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": "function [net, info] = cnn_mnist(varargin)\n% CNN_MNIST Demonstrated MatConNet on MNIST\n\nrun(fullfile(fileparts(mfilename('fullpath')),...\n '..', 'matlab', 'vl_setupnn.m')) ;\n\nopts.expDir = fullfile('data','mnist-baseline') ;\nopts.gpus = [];\nopts.pushbullet = []; % usage : pbNotify('accessToken'); from https://www.pushbullet.com/account\n[opts, varargin] = vl_argparse(opts, varargin) ;\n\nopts.dataDir = fullfile('data','mnist') ;\nopts.imdbPath = fullfile(opts.expDir, 'imdb.mat');\nopts.useBnorm = false ;\nopts.train.batchSize = 100 ;\nopts.train.numEpochs = 20 ;\nopts.train.continue = true ;\nopts.train.gpus = opts.gpus;\nopts.train.learningRate = 0.001 ;\nopts.train.expDir = opts.expDir ;\nopts.train.pushbullet = opts.pushbullet ;\nopts = vl_argparse(opts, varargin) ;\n\n% --------------------------------------------------------------------\n% Prepare data\n% --------------------------------------------------------------------\n\nif exist(opts.imdbPath, 'file')\n imdb = load(opts.imdbPath) ;\nelse\n imdb = getMnistImdb(opts) ;\n mkdir(opts.expDir) ;\n save(opts.imdbPath, '-struct', 'imdb') ;\nend\n\nnet = cnn_mnist_init('useBnorm', opts.useBnorm) ;\n\n% --------------------------------------------------------------------\n% Train\n% --------------------------------------------------------------------\n% b = [10 10] + [10 10 10] ; error test\n[net, info] = cnn_train(net, imdb, @getBatch, ...\n opts.train, ...\n 'val', find(imdb.images.set == 3)) ;\n\nif ~isempty(opts.pushbullet)\n opts.pushbullet.notify('training complete') ;\nend\n% --------------------------------------------------------------------\nfunction [im, labels] = getBatch(imdb, batch)\n% --------------------------------------------------------------------\nim = imdb.images.data(:,:,:,batch) ;\nlabels = imdb.images.labels(1,batch) ;\n\n% --------------------------------------------------------------------\nfunction imdb = getMnistImdb(opts)\n% --------------------------------------------------------------------\n% Preapre the imdb structure, returns image data with mean image subtracted\nfiles = {'train-images-idx3-ubyte', ...\n 'train-labels-idx1-ubyte', ...\n 't10k-images-idx3-ubyte', ...\n 't10k-labels-idx1-ubyte'} ;\n\nif ~exist(opts.dataDir, 'dir')\n mkdir(opts.dataDir) ;\nend\n\nfor i=1:4\n if ~exist(fullfile(opts.dataDir, files{i}), 'file')\n url = sprintf('http://yann.lecun.com/exdb/mnist/%s.gz',files{i}) ;\n fprintf('downloading %s\\n', url) ;\n gunzip(url, opts.dataDir) ;\n end\nend\n\nf=fopen(fullfile(opts.dataDir, 'train-images-idx3-ubyte'),'r') ;\nx1=fread(f,inf,'uint8');\nfclose(f) ;\nx1=permute(reshape(x1(17:end),28,28,60e3),[2 1 3]) ;\n\nf=fopen(fullfile(opts.dataDir, 't10k-images-idx3-ubyte'),'r') ;\nx2=fread(f,inf,'uint8');\nfclose(f) ;\nx2=permute(reshape(x2(17:end),28,28,10e3),[2 1 3]) ;\n\nf=fopen(fullfile(opts.dataDir, 'train-labels-idx1-ubyte'),'r') ;\ny1=fread(f,inf,'uint8');\nfclose(f) ;\ny1=double(y1(9:end)')+1 ;\n\nf=fopen(fullfile(opts.dataDir, 't10k-labels-idx1-ubyte'),'r') ;\ny2=fread(f,inf,'uint8');\nfclose(f) ;\ny2=double(y2(9:end)')+1 ;\n\nset = [ones(1,numel(y1)) 3*ones(1,numel(y2))];\ndata = single(reshape(cat(3, x1, x2),28,28,1,[]));\ndataMean = mean(data(:,:,:,set == 1), 4);\ndata = bsxfun(@minus, data, dataMean) ;\n\nimdb.images.data = data ;\nimdb.images.data_mean = dataMean;\nimdb.images.labels = cat(2, y1, y2) ;\nimdb.images.set = set ;\nimdb.meta.sets = {'train', 'val', 'test'} ;\nimdb.meta.classes = arrayfun(@(x)sprintf('%d',x),0:9,'uniformoutput',false) ;\n", "meta": {"author": "thomas-koehler", "repo": "SupER", "sha": "d8c6f2e4b26db002ff55bc2beba18639f1d0bb49", "save_path": "github-repos/MATLAB/thomas-koehler-SupER", "path": "github-repos/MATLAB/thomas-koehler-SupER/SupER-d8c6f2e4b26db002ff55bc2beba18639f1d0bb49/matlab/algorithms/SRAlgorithms/DRCN/snu_matconvnet/examples/cnn_mnist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3979221490809678}}
{"text": "validInputSize = [3,3,18,1];\nlayer = yolov3Layer('yolov3', rand(3,2),1,1,[416,416],'default');\ncheckLayer(layer,validInputSize,'ObservationDimension' ,4)\n\n%%\nlayer = mishLayer('mishACT');\nvalidInputSize = [24 24 20];\ncheckLayer(layer,validInputSize,'ObservationDimension',4)\n\n\n", "meta": {"author": "cuixing158", "repo": "yolov3-yolov4-matlab", "sha": "94a2b1218e62754e08e83c2e0e857b58db06d3f9", "save_path": "github-repos/MATLAB/cuixing158-yolov3-yolov4-matlab", "path": "github-repos/MATLAB/cuixing158-yolov3-yolov4-matlab/yolov3-yolov4-matlab-94a2b1218e62754e08e83c2e0e857b58db06d3f9/CustomLayers/mycheckLayer.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.39792214312981616}}
{"text": "filename='ImprovedCantilever_hexahedra';\n ptype = 'MACRO';\nmethod = 'SIMPALL';\nmaterialType = 'ISOTROPIC';\ninitial_case = 'full';\ncost = {'compliance'};\nweights = [1, 0.1];\nconstraint = {'volumeConstraint'};\noptimizer = 'SLERP'; incrementFactor = 1;\nfilterType = 'P1';\n\nnsteps = 1;\nVfrac_final = 0.1;\nPerimeter_target = 1;\noptimality_final = 1e-3;\nconstr_final =1e-3;\n\nVfrac_initial = 1;\noptimality_initial = 1e-2;\nconstr_initial = 1e-3;\nTOL.rho_plus = 1;\nTOL.rho_minus = 0;\nTOL.E_plus = 1;\nTOL.E_minus = 1e-3;\nTOL.nu_plus = 1/3;\nTOL.nu_minus = 1/3;", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/Topology Optimization/Benchmarks/ImprovedCantilever&Bridge/ImpCantileverHexahedra_Case_1_1_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.5, "lm_q1q2_score": 0.39782905487702597}}
{"text": "function varargout = spm_render_vol(varargin)\n% surface render a memory mapped 8 bit image - a compiled routine\n% FORMAT [REN, ZBUF, X, Y, Z] = spm_render_vol(V, A, [i j], [u n])\n% V - is the memory mapped volume\n% A - {4 x 4} affine transformation matrix\n% [i j] - dimensions of REN\n% [u n] - u is threhsold at which voxels are 'solid'\n% n is the number of nearest neighbours to use to determine the\n% surface orientation\n% REN - is the rendered image\n% ZBUF - distance from the view plane to the object's surface\n% X, Y, Z - are images containing the coordinates of the voxels on the\n% surface of the volume.\n%_______________________________________________________________________\n%\n% [i j] defines the two dimensions of the output image. The coordinates\n% in 3-D space of the voxels in this image are assumed to range from\n% 1,1,0 to i,j,0.\n%\n% For each pixel in the volume, the coordinates (x,y,z & 1) are\n% multiplied by the matrix A, to give the image coordinates that these\n% voxels map to.\n%\n% The threshold at which voxels are assumed to be solid pertains to the\n% 8-bit data i.e. {0 - 255}\n%\n% Illumination is assumed to be from the viewplane\n%\n%_______________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% John Ashburner\n% $Id: spm_render_vol.m 1143 2008-02-07 19:33:33Z spm $\n\n\n%-This is merely the help file for the compiled routine\nerror('spm_render_vol.c not compiled - see Makefile')\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_render_vol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.39775724579733207}}
{"text": "function res = SPIRiT(kernel,method, imSize)\n%res = SPIRiT(kernel [,method, imSize])\n%\tImplementation of the SPIRiT kernel operator\n%\n% \n% Constructor inputs:\n% kernel: [kx,ky,nCoils, nCoils] the spirit 2D convolution kernel.\n% See corrMatrix.m, calibrate.m and the demos on how to\n% generate a kernel.\n% method: implementation type of the operator. There are three\n% 'conv' is a k-space convolution implementation (slowest)\n% that operates on k-space data and produces k-space data.\n% 'fft' is an fft based implementation of the k-space\n% convolution through image domain multiplication. \n% It operates on k-sapce data and produces k-space data. \n% 'image' The SPIRiT operator is applied to image space data.\n% This is useful when using image-based non-cartesian\n% reconstruction. In this case the SPIRiT operator\n% operates on image data and produces image data. \n%\n% imSize: Size of the resulting image (only needed for 'fft' and\n% 'image' modes\n%\n%\n% Example:\n%\n% [x,y] = meshgrid(linspace(0,1,128));\n% % Generate fake Sensitivity maps\n% sMaps = cat(3,x.^2,1-x.^2,y.^2,1-y.^2);\n% % generate 4 coil phantom\n% imgs = repmat(phantom(128),[1,1,4]).*sMaps;\n% DATA = fft2c(imgs);\n% % crop 20x20 window from the center of k-space for calibration\n% kCalib = crop(DATA,[20,20,4]);\n%\n% %calibrate a kernel\n% kSize = [5,5];\n% coils = 4;\n% kernel = zeros([kSize,coils,coils]);\n% [AtA,] = corrMatrix(kCalib,kSize);\n% for n=1:coils\n% kernel(:,:,:,n) = calibrate(AtA,kSize,coils,n,0.01);\n% end\n% GOP = SPIRiT(kernel, 'fft',[128,128]);\n%\n% % undersample by a factor of 2\n% DATA(1:2:end,2:2:end,:) = 0;\n% DATA(2:2:end,1:2:end,:) = 0;\n% \n% %reconstruct:\n% [res] = cgSPIRiT(DATA,GOP, 20, 1e-5, DATA);\n% figure, imshow(cat(2,sos(imgs), 2*sos(ifft2c(DATA)), sos(ifft2c(res))),[]);\n% title('full, zero-fill, result')\n% \n% See Also:\n% calibrate.m, corrMatrix.m\n%\n% (c) Michael Lustig 2007\n \n\n if nargin < 2\n\t method = 'conv';\n\t KERNEL = [];\n end\n \n if strcmp(method,'conv')==1\n\t KERNEL = [];\n end\n\n\n if strcmp(method,'fft')==1 & nargin < 3\n\t error('must provide image size');\n end\n\n % for methods 'fft' and 'image' precompute the image domain kernel by\n % zero-padding and inverse fft\n \n if strcmp(method,'fft')==1 | strcmp(method,'image')==1\n\t for n=1:size(kernel,4)\n KERNEL(:,:,:,n) = ifftnshift(zpad(kernel(end:-1:1,end:-1:1,:,n), imSize(1), imSize(2), size(kernel,3)),1:2);\n% KERNEL(:,:,:,n) = (ifft2c(zpad(kernel(end:-1:1,end:-1:1,:,n)*sqrt(imSize(1)*imSize(2)), imSize(1), imSize(2), size(kernel,3))));\n end\n end\n\n \n\n if strcmp(method,'fft')==0 & strcmp(method,'conv')==0 & strcmp(method,'image')==0\n\t eror('no such method');\n end\n\n \n res.kernel = kernel;\n res.adjoint = 0;\n res.KERNEL = KERNEL;\n res.method = method;\n res.imSize = imSize;\n res = class(res,'SPIRiT');\n\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/@SPIRiT/SPIRiT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.39775724579733207}}
{"text": "function [hc] = read_ctf_hc(filename);\n\n% READ_CTF_HC reads the MEG headcoil marker positions from an ascii file\n% and computes the coordinate transformation required to get from from\n% dewar to head-coordinates\n%\n% the definition of head coordinates is according to CTF standard:\n% - the origin is exactly between LPA and RPA\n% - the positive x-axis goes throught NAS\n% - the positive y-axis goes (approximately) through LPA\n% - the positive z-axis goes up, orthogonal to the x- and y-axes\n%\n% hc = read_ctf_hc(filename)\n%\n% returns a structure with the following fields\n% hc.dewar.nas\tmarker positions relative to dewar \n% hc.dewar.lpa\n% hc.dewar.rpa\n% hc.head.nas\t\tmarker positions relative to head (measured) \n% hc.head.lpa\n% hc.head.rpa\n% hc.standard.nas\tmarker positions relative to head (expected)\n% hc.standard.lpa\n% hc.standard.rpa\n% and\n% hc.affine\t\tparameter for affine transformation (1x12)\n% hc.homogenous\thomogenous transformation matrix (4x4, see warp3d)\n% hc.translation\ttranslation vector (1x3)\n% hc.rotation\t\trotation matrix (3x3)\n% \n% Gradiometer positions can be transformed into head coordinates using the \n% homogeneous transformation matrix, or using the affine parameters and\n% the warp3d function from the WARPING toolbox\n% \n% WARNING: all returned positions are in mm, and the transformation matrices\n% also should be applied on channel positions that are in mm.\n\n% Copyright (C) 2002, Robert Oostenveld\n% \nglobal fb\n\nhc.standard.nas = [0 0 0];\nhc.standard.lpa = [0 0 0];\nhc.standard.rpa = [0 0 0];\nhc.dewar.nas = [0 0 0];\nhc.dewar.lpa = [0 0 0];\nhc.dewar.rpa = [0 0 0];\nhc.head.nas = [0 0 0];\nhc.head.lpa = [0 0 0];\nhc.head.rpa = [0 0 0];\n\nfid = fopen(filename, 'r');\nif fid==-1\n error(sprintf('could not open file %s', filename));\nend\n\nfseek(fid, 0, 'bof');\nline = [];\n\nif fb\n fprintf('reading standard coil positions with respect to the dewar\\n');\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% standard coil positions with respect to the dewar\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nwhile ~strcmp(line, 'standard nasion coil position relative to dewar (cm):')\n line = fgetl(fid);\n if ~ischar(line) & line==-1, error('premature end of file'), end\nend\nline = fgetl(fid); [t, r] = strtok(line, '='); hc.standard.nas(1) = str2num(r(2:end));\nline = fgetl(fid); [t, r] = strtok(line, '='); hc.standard.nas(2) = str2num(r(2:end));\nline = fgetl(fid); [t, r] = strtok(line, '='); hc.standard.nas(3) = str2num(r(2:end));\n% NOTE THAT THERE IS AN TYPING ERROR IN SOME CTF FILES WHICH I HAVE TO REPRODUCE HERE (staNdard)\nwhile ~(strcmp(line, 'stadard left ear coil position relative to dewar (cm):') | ...\n strcmp(line, 'standard left ear coil position relative to dewar (cm):'))\n line = fgetl(fid);\n if ~ischar(line) & line==-1, error('premature end of file'), end\nend\nline = fgetl(fid); [t, r] = strtok(line, '='); hc.standard.lpa(1) = str2num(r(2:end));\nline = fgetl(fid); [t, r] = strtok(line, '='); hc.standard.lpa(2) = str2num(r(2:end));\nline = fgetl(fid); [t, r] = strtok(line, '='); hc.standard.lpa(3) = str2num(r(2:end));\nwhile ~strcmp(line, 'standard right ear coil position relative to dewar (cm):')\n line = fgetl(fid);\n if ~ischar(line) & line==-1, error('premature end of file'), end\nend\nline = fgetl(fid); [t, r] = strtok(line, '='); hc.standard.rpa(1) = str2num(r(2:end));\nline = fgetl(fid); [t, r] = strtok(line, '='); hc.standard.rpa(2) = str2num(r(2:end));\nline = fgetl(fid); [t, r] = strtok(line, '='); hc.standard.rpa(3) = str2num(r(2:end));\n\nif fb\n fprintf('reading measured coil positions with respect to the dewar\\n');\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% measured coil positions with respect to the dewar\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nwhile ~strcmp(line, 'measured nasion coil position relative to dewar (cm):')\n line = fgetl(fid);\n if ~ischar(line) & line==-1, error('premature end of file'), end\nend\nline = fgetl(fid); [t, r] = strtok(line, '='); hc.dewar.nas(1) = str2num(r(2:end));\nline = fgetl(fid); [t, r] = strtok(line, '='); hc.dewar.nas(2) = str2num(r(2:end));\nline = fgetl(fid); [t, r] = strtok(line, '='); hc.dewar.nas(3) = str2num(r(2:end));\nwhile ~strcmp(line, 'measured left ear coil position relative to dewar (cm):')\n line = fgetl(fid);\n if ~ischar(line) & line==-1, error('premature end of file'), end\nend\nline = fgetl(fid); [t, r] = strtok(line, '='); hc.dewar.lpa(1) = str2num(r(2:end));\nline = fgetl(fid); [t, r] = strtok(line, '='); hc.dewar.lpa(2) = str2num(r(2:end));\nline = fgetl(fid); [t, r] = strtok(line, '='); hc.dewar.lpa(3) = str2num(r(2:end));\nwhile ~strcmp(line, 'measured right ear coil position relative to dewar (cm):')\n line = fgetl(fid);\n if ~ischar(line) & line==-1, error('premature end of file'), end\nend\nline = fgetl(fid); [t, r] = strtok(line, '='); hc.dewar.rpa(1) = str2num(r(2:end));\nline = fgetl(fid); [t, r] = strtok(line, '='); hc.dewar.rpa(2) = str2num(r(2:end));\nline = fgetl(fid); [t, r] = strtok(line, '='); hc.dewar.rpa(3) = str2num(r(2:end));\n\nif fb\n fprintf('reading measured coil positions with respect to the head\\n');\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% measured coil positions with respect to the head\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nwhile ~strcmp(line, 'measured nasion coil position relative to head (cm):')\n line = fgetl(fid);\n if ~ischar(line) & line==-1, error('premature end of file'), end\nend\nline = fgetl(fid); [t, r] = strtok(line, '='); hc.head.nas(1) = str2num(r(2:end));\nline = fgetl(fid); [t, r] = strtok(line, '='); hc.head.nas(2) = str2num(r(2:end));\nline = fgetl(fid); [t, r] = strtok(line, '='); hc.head.nas(3) = str2num(r(2:end));\nwhile ~strcmp(line, 'measured left ear coil position relative to head (cm):')\n line = fgetl(fid);\n if ~ischar(line) & line==-1, error('premature end of file'), end\nend\nline = fgetl(fid); [t, r] = strtok(line, '='); hc.head.lpa(1) = str2num(r(2:end));\nline = fgetl(fid); [t, r] = strtok(line, '='); hc.head.lpa(2) = str2num(r(2:end));\nline = fgetl(fid); [t, r] = strtok(line, '='); hc.head.lpa(3) = str2num(r(2:end));\nwhile ~strcmp(line, 'measured right ear coil position relative to head (cm):')\n line = fgetl(fid);\n if ~ischar(line) & line==-1, error('premature end of file'), end\nend\nline = fgetl(fid); [t, r] = strtok(line, '='); hc.head.rpa(1) = str2num(r(2:end));\nline = fgetl(fid); [t, r] = strtok(line, '='); hc.head.rpa(2) = str2num(r(2:end));\nline = fgetl(fid); [t, r] = strtok(line, '='); hc.head.rpa(3) = str2num(r(2:end));\n\nfclose(fid);\n\nif fb\n fprintf('computing transformation matrix\\n');\nend\n\n% change the marker positions from cm to mm\nhc.standard.nas = 10*hc.standard.nas;\nhc.standard.lpa = 10*hc.standard.lpa;\nhc.standard.rpa = 10*hc.standard.rpa;\nhc.dewar.nas = 10*hc.dewar.nas;\nhc.dewar.lpa = 10*hc.dewar.lpa;\nhc.dewar.rpa = 10*hc.dewar.rpa;\nhc.head.nas = 10*hc.head.nas;\nhc.head.lpa = 10*hc.head.lpa;\nhc.head.rpa = 10*hc.head.rpa;\n\n% compute the direction of the head coordinate axes in dewar coordinates\nd_x = hc.dewar.nas - (hc.dewar.lpa + hc.dewar.rpa)/2;\nd_z = cross(d_x, hc.dewar.lpa - hc.dewar.rpa);\nd_y = cross(d_z, d_x);\nd_x = d_x / norm(d_x);\nd_y = d_y / norm(d_y);\nd_z = d_z / norm(d_z);\n\n% compute the translation and rotation which are neccessary to transform\n% any given location from the dewar to the head coordinate system\nhc.translation = -(hc.dewar.lpa + hc.dewar.rpa)/2;\nhc.rotation = inv([d_x' d_y' d_z']);\n\n% construct the homogenous coordinate transformation matrix\n% from the subsequent translation and rotation\nhc.homogenous = eye(4,4);\nhc.homogenous(1:3,4) = hc.rotation * hc.translation';\nhc.homogenous(1:3,1:3) = hc.rotation;\n\n% construct a vector with the 12 parameters for an affine warp\nhc.affine = hc.homogenous';\nhc.affine = hc.affine(1:12);\n\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/plugins/ctfimport1.03/read_ctf_hc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.397757245797332}}
{"text": "function score = score_all_subid(M,sid,bid,lib)\n%\n% For a MotorProgram M, compute the log-score of switching\n% its \"sub-stroke id\" to every other possibility\n%\n% Input\n% sid: stroke index\n% bid: sub-stroke index\n%\n% Output\n% score: [nclust x 1] score for each possibility, using all CPDs\n% that directly depend on it\n%\n assert(numel(sid)==1);\n assert(numel(bid)==1);\n ncat = lib.N;\n \n seq_score = zeros(ncat,1);\n \n % Score the transition TO the current primitive \n if bid == 1 % first primitive\n seq_score = seq_score + lib.logStart(:);\n else % not the first\n prev_subid = M.S{sid}.ids(bid-1);\n seq_score = seq_score + vec(lib.logT(prev_subid,1:ncat));\n end\n \n % Score the transition AWAY from the current primitive\n if bid < M.S{sid}.nsub\n next_subid = M.S{sid}.ids(bid+1);\n seq_score = seq_score + vec(lib.logT(1:ncat,next_subid));\n end\n \n % Scale term\n invscale_type = M.S{sid}.invscales_type(bid);\n rep_invscale_type = repmat(invscale_type,[ncat 1]);\n \n % Shape term\n if ~isempty(M.S{sid}.shapes_type)\n shape_type = M.S{sid}.shapes_type(:,:,bid);\n rep_shape_type = repmat(shape_type,[1 1 ncat]);\n shape_score = CPD.score_shape_type(lib,rep_shape_type,1:ncat);\n else\n shape_token = M.S{sid}.shapes_token(:,:,bid);\n rep_shape_token = repmat(shape_token,[1 1 ncat]);\n shape_score = CPD.score_shape_marginalize(lib,rep_shape_token,1:ncat);\n end\n \n % compute scores \n scale_score = CPD.score_invscale_type(lib,rep_invscale_type,1:ncat);\n score = seq_score + scale_score + shape_score;\nend", "meta": {"author": "brendenlake", "repo": "BPL", "sha": "2c7f679bb0055f29cbade7ef099897c3342bcb79", "save_path": "github-repos/MATLAB/brendenlake-BPL", "path": "github-repos/MATLAB/brendenlake-BPL/BPL-2c7f679bb0055f29cbade7ef099897c3342bcb79/mcmc/score_all_subid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3977572405175171}}
{"text": "% -------------------------------------------------------------------------------------------------------------------------\nclassdef XCorr < dagnn.Layer\n%XCORR\n% Crosscorrelates two activations of different size exploiting the API of vl_nnconv\n%\n% Luca Bertinetto, Jack Valmadre, Joao F. Henriques, 2016\n% -------------------------------------------------------------------------------------------------------------------------\n properties\n opts = {'cuDNN'}\n end\n\n methods\n function outputs = forward(obj, inputs, params)\n assert(numel(inputs) == 2, 'two inputs are needed');\n\n z = inputs{1}; % exemplar\n x = inputs{2}; % instance (search region)\n\n% assert(ndims(z) == ndims(x), 'z and x have different number of dimensions');\n% assert(size(z,1) <= size(x,1), 'exemplar z has to be smaller than instance x');\n% \n% [wx,hx,cx,bx] = size(x);\n% x = reshape(x, [wx,hx,cx*bx,1]);\n% o = vl_nnconv(x, z, []);\n% [wo,ho,co,bo] = size(o);\n% assert(co==bx);\n% outputs{1} = reshape(o, [wo,ho,bo,co]);\n% [w,h,c] = size(x);\n% x = reshape(x,[w,h,c,1]);\n outputs{1} = vl_nnconv(x, z, []);\n end\n\n function [derInputs, derParams] = backward(obj, inputs, params, derOutputs)\n assert(numel(inputs) == 2, 'two inputs are needed');\n assert(numel(derOutputs) == 1, 'only one gradient should be flowing in this layer (dldy)');\n z = inputs{1}; % exemplar\n x = inputs{2}; % instance\n assert(size(z,1) < size(x,1), 'exemplar z has to be smaller than instance x');\n [wx,hx,cx,bx] = size(x);\n x = reshape(x, [wx,hx,cx*bx,1]);\n dldy = derOutputs{1};\n [wdl,hdl,cdl,bdl] = size(dldy);\n assert(cdl==1);\n dldy = reshape(dldy, [wdl,hdl,cdl*bdl,1]);\n [dldx, dldz, ~] = vl_nnconv(x, z, [], dldy);\n [mx,nx,cb,one] = size(dldx);\n assert(mx == size(x, 1));\n assert(nx == size(x, 2));\n assert(cb == cx * bx);\n assert(one == 1);\n derInputs{1} = dldz;\n derInputs{2} = reshape(dldx, [mx,nx,cx,bx]);\n derParams = {};\n end\n\n function outputSizes = getOutputSizes(obj, inputSizes)\n z_sz = inputSizes{1};\n x_sz = inputSizes{2};\n y_sz = [x_sz(1:2) - z_sz(1:2) + 1, 1, z_sz(4)];\n outputSizes = {y_sz};\n end\n\n function rfs = getReceptiveFields(obj)\n rfs(1,1).size = [inf inf]; % could be anything\n rfs(1,1).stride = [1 1];\n rfs(1,1).offset = 1;\n rfs(2,1).size = [inf inf];\n rfs(2,1).stride = [1 1];\n rfs(2,1).offset = 1;\n end\n\n function obj = XCorr(varargin)\n obj.load(varargin);\n end\n\n end\n\nend\n", "meta": {"author": "XinLi-zn", "repo": "TADT", "sha": "659e031a9c40624d53b7b1d4d25f16cd70795c3b", "save_path": "github-repos/MATLAB/XinLi-zn-TADT", "path": "github-repos/MATLAB/XinLi-zn-TADT/TADT-659e031a9c40624d53b7b1d4d25f16cd70795c3b/tracking/XCorr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.3976680275264534}}
{"text": "function varargout= proc_laplacian(dat, varargin)\n%PROC_LAPLACIAN - Apply spatial Laplacian filter to signals\n%\n%Synopsis:\n% [DAT_LAP, LAP_W]= proc_laplacian(DAT, )\n%\n%Arguments:\n% DAT: data structure of continuous or epoched data\n% OPT: struct or proerty/value list of optional properties:\n% .filterType - {small, large, horizontal, vertical, diagonal, eight},\n% default 'small'\n% .clab - channels that are to be obtained, default '*'.\n% .ignoreClab: labels of channels to be ignored, default {'E*'}.\n% .requireCompleteNeighborhood\n% .requireCompleteOutput\n% .verbose\n%\n%Returns:\n% DAT_LAP: updated data structure\n% LAP_W: filter matrix that can be used, e.g. in proc_linearDerivation\n%\n%See also:\n% procutil_getClabForLaplacian, proc_linearDerivation\n\n% Benjamin Blankertz\n% 07-2012 Johannes Hoehne - Updated documentation and parameter naming\n\n\nprops= {'clab' '*' '!CHAR';\n 'IgnoreCLab' {'E*'} 'CHAR|CELL{CHAR}'\n 'CopyCLab' {'E*'} 'CHAR|CELL{CHAR}'\n 'requireCompleteNeighborhood' 1 '!BOOL' \n 'requireCompleteOutput' 0 '!BOOL' \n 'appendix' ' lap' 'CHAR' \n 'verbose' 0 'BOOL'\n 'GridFcn' @util_gridForLaplacian 'FUNC'\n 'FilterType' 'small' 'CHAR(small large horizontal vertical bip_to_anterior bip_to_posterior bip_to_left bip_to_right diagonal diagonal_small)'\n };\n\nif nargin==0,\n varargout{1} = props; \n return\nend\n\ndat = misc_history(dat);\nopt= opt_proplistToStruct(varargin{:});\n[opt, isdefault]= opt_setDefaults(opt, props);\nopt_checkProplist(opt, props);\n\nmisc_checkType(dat, 'STRUCT(clab)');\n\nif ~iscell(opt.IgnoreCLab),\n opt.IgnoreCLab= {opt.IgnoreCLab};\nend\n\nlaplace= [];\nlaplace.grid= opt.GridFcn();\nif isnumeric(opt.FilterType),\n laplace.filter= opt.FilterType;\nelse\n laplace.filter= procutil_lapGetLaplacianFilter(opt.FilterType);\nend\n\nif ~isstruct(dat),\n dat= struct('clab',{dat});\nend\n\nrc= util_chanind(dat, {'not', opt.IgnoreCLab{:}});\nnOrigChans= length(dat.clab);\npos= zeros(2, nOrigChans);\nfor ic= 1:nOrigChans,\n pos(:,ic)= procutil_lapGetCoordinates(dat.clab{ic}, laplace.grid);\nend\npos(:,setdiff(1:nOrigChans,rc,'legacy'))= inf;\n\nidx_tbf= util_chanind(dat, opt.clab);\nW= zeros(length(dat.clab), length(idx_tbf));\nclab = [];\nlc= 0;\nfor ci= 1:length(idx_tbf),\n cc= idx_tbf(ci);\n refChans= [];\n nRefs= size(laplace.filter,2);\n for ir= 1:nRefs,\n ri= find( pos(1,:)==pos(1,cc)+laplace.filter(1,ir) & ...\n pos(2,:)==pos(2,cc)+laplace.filter(2,ir) );\n refChans= [refChans ri];\n end\n if length(refChans)==nRefs | ~opt.requireCompleteNeighborhood,\n lc= lc+1;\n W(cc,lc)= 1;\n if ~isempty(refChans),\n W(refChans,lc)= -1/length(refChans);\n end\n clab= [clab, dat.clab(cc)];\n if opt.verbose,\n fprintf('%s: ref''ed to: %s\\n', ...\n dat.clab{cc}, str_vec2str(dat.clab(refChans)));\n end\n elseif opt.requireCompleteOutput,\n error('channel %s has incomplete neighborhood', dat.clab{cc});\n end\nend\nW= W(:,1:lc);\n\nif isfield(dat, 'x'),\n out= proc_linearDerivation(dat, W, 'clab', strcat(clab, opt.appendix));\n if ~isempty(opt.CopyCLab),\n idx= util_chanind(dat, opt.CopyCLab);\n if ~isempty(idx),\n out.x= cat(2, out.x, dat.x(:,idx,:));\n out.clab= cat(2, out.clab, dat.clab(idx));\n end\n end\n varargout= {out, W};\nelse\n varargout= {W};\nend\n", "meta": {"author": "bbci", "repo": "bbci_public", "sha": "2e6fe9481537dcfee702e74544191dcf737f02ce", "save_path": "github-repos/MATLAB/bbci-bbci_public", "path": "github-repos/MATLAB/bbci-bbci_public/bbci_public-2e6fe9481537dcfee702e74544191dcf737f02ce/processing/proc_laplacian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.3976680275264534}}
{"text": "function [newgt, newdet] = dropObjectsInIgr(gt, det, imgHeight, imgWidth)\n%% drop objects in ignored region\nnewgt = [];\nnewdet = [];\nnumFr = max(gt(:,1));\nfor fr = 1:numFr\n % parse objects\n idxGtFr = gt(:,1) == fr & gt(:, 8) ~= 0;\n curgt = gt(idxGtFr,:);\n idxDetFr = det(:,1) == fr;\n curdet = det(idxDetFr,:); \n % parse ignored regions\n idxIgr = gt(:,1) == fr & gt(:, 8) == 0;\n igrRegion = gt(idxIgr, 3:6);\n if(~isempty(igrRegion))\n igrMap = zeros(imgHeight, imgWidth);\n numIgr = size(igrRegion,1);\n for j = 1:numIgr\n igrMap(igrRegion(j,2):min(imgHeight,igrRegion(j,2)+igrRegion(j,4)),igrRegion(j,1):min(imgWidth,igrRegion(j,1)+igrRegion(j,3))) = 1;\n end\n intIgrMap = createIntImg(double(igrMap));\n idxLeft = [];\n for i = 1:size(curgt, 1)\n pos = max(1,round(curgt(i,3:6)));\n x = max(1, min(imgWidth, pos(1)));\n y = max(1, min(imgHeight, pos(2)));\n w = pos(3);\n h = pos(4);\n tl = intIgrMap(y, x);\n tr = intIgrMap(y, min(imgWidth,x+w));\n bl = intIgrMap(max(1,min(imgHeight,y+h)), x);\n br = intIgrMap(max(1,min(imgHeight,y+h)), min(imgWidth,x+w));\n igrVal = tl + br - tr - bl; \n if(igrVal/(h*w)<0.5)\n idxLeft = cat(1, idxLeft, i);\n end\n end\n \n curdet = curdet(idxLeft, :);\n idxLeft = [];\n for i = 1:size(curdet, 1)\n pos = max(1,round(curdet(i,3:6)));\n x = max(1, min(imgWidth, pos(1)));\n y = max(1, min(imgHeight, pos(2)));\n w = pos(3);\n h = pos(4);\n tl = intIgrMap(y, x);\n tr = intIgrMap(y, min(imgWidth,x+w));\n bl = intIgrMap(max(1,min(imgHeight,y+h)), x);\n br = intIgrMap(max(1,min(imgHeight,y+h)), min(imgWidth,x+w));\n igrVal = tl + br - tr - bl; \n if(igrVal/(h*w)<0.5)\n idxLeft = cat(1, idxLeft, i);\n end\n end\n curdet = curdet(idxLeft, :); \n end\n newgt = cat(1, newgt, curgt);\n newdet = cat(1, newdet, curdet);\n \nend", "meta": {"author": "VisDrone", "repo": "DroneCrowd", "sha": "3d25637f93f9476b4c949b6b9362287635b1a8c3", "save_path": "github-repos/MATLAB/VisDrone-DroneCrowd", "path": "github-repos/MATLAB/VisDrone-DroneCrowd/DroneCrowd-3d25637f93f9476b4c949b6b9362287635b1a8c3/STNNet/DroneCrowd-VID-toolkit/utils/dropObjectsInIgr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.3976584615158062}}
{"text": "function D = tsss_spm_momentspace(S)\n% Switch a dataset to SSS space using virtual montage\n% FORMAT D = spm_eeg_crop(S)\n%\n% S - input struct\n% fields of S:\n% D - MEEG object or filename of M/EEG mat-file with data after\n% TSSS tool\n% condthresh - threshold on condition number for regularisation\n%\n% Output:\n% D - MEEG object (also written on disk)\n%\n% Reference: Vrba J, Taulu S, Nenonen J, Ahonen A. Signal space separation\n% beamformer. Brain Topogr. 2010 Jun;23(2):128-33.\n%__________________________________________________________________________\n% Copyright (C) 2014 Wellcome Trust Centre for Neuroimaging\n\n% Vladimir Litvak\n% $Id: tsss_spm_momentspace.m 7703 2019-11-22 12:06:29Z guillaume $\n\nSVNrev = '$Rev: 7703 $';\n\n%-Startup\n%--------------------------------------------------------------------------\nspm('FnBanner', mfilename, SVNrev);\nspm('FigName','TSSS momenspace transformation'); spm('Pointer','Watch');\n\nif ~isfield(S, 'condthresh'), S.condthresh = 80; end\n\nD = spm_eeg_load(S.D);\n\nif ~isfield(D, 'SSS')\n error('Run the TSSS tool first');\nend\n\nD = montage(D, 'clear');\n\nSSS = D.SSS;\n\n[SN_new, sss_indices , nmodes] = basis_condition_adjustment(SSS(1).SN, size(SSS.SNin, 2), S.condthresh);\npSN = pinv(SN_new);\npSN = pSN(1:nmodes, :);\n\nlabelnew = {};\nfor i = 1:nmodes\n labelnew{i} = ['moment' num2str(i)];\nend\n\nmont = [];\nmont.labelorg = D.chanlabels(D.indchantype('MEGANY'))';\nmont.labelnew = labelnew;\nmont.tra = pSN;\n\nif ~isempty(S.addchannels)\n chantypeorg = D.chantype(D.indchannel(S.addchannels));\n chanunitorg = D.units(D.indchannel(S.addchannels));\n for c = 1:numel(S.addchannels)\n mont.labelorg(end+1) = S.addchannels(c);\n mont.labelnew(end+1) = S.addchannels(c);\n mont.tra(end+1, end+1) = 1;\n end\nend\n\nD = montage(D, 'add', mont);\nD = chantype(D, strmatch('moment', D.chanlabels), 'MEG');\nD = units(D, strmatch('moment', D.chanlabels), 'fT');\n\nif ~isempty(S.addchannels)\n D = chantype(D, D.indchannel(S.addchannels), chantypeorg);\n D = units(D, D.indchannel(S.addchannels), chanunitorg);\nend\n\nD = badchannels(D, D.indchantype('MEGANY'), 0);\n\nsave(D);\n\nspm('FigName','TSS momenspace transformation: done'); spm('Pointer','Arrow');", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/TSSS/tsss_spm_momentspace.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.3976584615158062}}
{"text": "function fig_hdl = img2curve\n% img2curve\n%-------------------------------------------------------------------------------\n% File name : img2curve.m \n% Generated on: 11-Mar-2013 10:54:18 \n% Description :\n% \n% img2curve helps import data from a graph in a photo file, received from a\n% scan, catalog, pdf etc. by marking points on the curve.\n% Output will include the marked points and a polynomial fit.\n% Work flow:\n% 1. Load image file.\n% 2. Mark scale size for X and Y axis.\n% 3. Set a value for a point on the image (0,0 or other) to locate CS.\n% 4. Mark curve points.\n% 5. Export to mat file, excel or work space.\n% \n% Good Luck,\n% Amihay Blau\n\n%-------------------------------------------------------------------------------\n\n\n% Initialize handles structure\nhandles = struct();\n\n% Create all UI controls\nbuild_gui();\n\n% Assign function output\nfig_hdl = handles.img2curve_figure;\n\n%% ---------------------------------------------------------------------------\n\tfunction build_gui()\n% Creation of all uicontrols\n\n\t\t% --- FIGURE -------------------------------------\n\t\thandles.img2curve_figure = figure( ...\n\t\t\t'Tag', 'img2curve_figure', ...\n\t\t\t'Units', 'centimeters', ...\n\t\t\t'Position', [4.9968253125 8.46023333333333 8.38091864583333 12.2673383333333], ...\n\t\t\t'Name', 'img2curve', ...\n\t\t\t'MenuBar', 'none', ...\n\t\t\t'NumberTitle', 'off', ...\n\t\t\t'Color', [0.804 0.878 0.969], ...\n\t\t\t'Resize', 'on');\n\n\t\t% --- PANELS -------------------------------------\n\t\thandles.import_uipanel = uipanel( ...\n\t\t\t'Parent', handles.img2curve_figure, ...\n\t\t\t'Tag', 'import_uipanel', ...\n\t\t\t'UserData', zeros(1,0), ...\n\t\t\t'Units', 'centimeters', ...\n\t\t\t'Position', [0.264382291666667 7.34982770833334 8.0107834375 4.70600479166667], ...\n\t\t\t'FontSize', 12, ...\n\t\t\t'BackgroundColor', [0.839 0.91 0.851], ...\n\t\t\t'Title', 'Import Image');\n\n\t\thandles.curve_uipanel = uipanel( ...\n\t\t\t'Parent', handles.img2curve_figure, ...\n\t\t\t'Tag', 'curve_uipanel', ...\n\t\t\t'UserData', zeros(1,0), ...\n\t\t\t'Units', 'centimeters', ...\n\t\t\t'Position', [0.264382291666667 3.7277903125 8.0107834375 3.48984625], ...\n\t\t\t'FontSize', 12, ...\n\t\t\t'BackgroundColor', [0.839 0.91 0.851], ...\n\t\t\t'Title', 'Define Curve');\n\n\t\thandles.save_uipanel = uipanel( ...\n\t\t\t'Parent', handles.img2curve_figure, ...\n\t\t\t'Tag', 'save_uipanel', ...\n\t\t\t'UserData', zeros(1,0), ...\n\t\t\t'Units', 'centimeters', ...\n\t\t\t'Position', [0.264382291666667 0.211505833333333 8.0107834375 3.35765510416667], ...\n\t\t\t'FontSize', 12, ...\n\t\t\t'BackgroundColor', [0.839 0.91 0.851], ...\n\t\t\t'Title', 'Save Curve Data');\n\n\t\t% --- STATIC TEXTS -------------------------------------\n\t\thandles.import_xScale_text = uicontrol( ...\n\t\t\t'Parent', handles.import_uipanel, ...\n\t\t\t'Tag', 'import_xScale_text', ...\n\t\t\t'Style', 'text', ...\n\t\t\t'Units', 'normalized', ...\n\t\t\t'Position', [0.381270903010033 0.33116883116883 0.535117056856187 0.246753246753247], ...\n\t\t\t'FontSize', 10, ...\n\t\t\t'BackgroundColor', [0.839 0.91 0.851], ...\n\t\t\t'String', {'X Scale','Y Scale'}, ...\n\t\t\t'HorizontalAlignment', 'left');\n\n\t\thandles.curve_PolOrder_text = uicontrol( ...\n\t\t\t'Parent', handles.curve_uipanel, ...\n\t\t\t'Tag', 'curve_PolOrder_text', ...\n\t\t\t'Style', 'text', ...\n\t\t\t'Units', 'normalized', ...\n\t\t\t'Position', [0.468227424749164 0.722222222222222 0.337792642140468 0.175925925925926], ...\n\t\t\t'FontSize', 10, ...\n\t\t\t'BackgroundColor', [0.839 0.91 0.851], ...\n\t\t\t'String', 'Polynom Order');\n\n\t\thandles.curve_Pol_text = uicontrol( ...\n\t\t\t'Parent', handles.curve_uipanel, ...\n\t\t\t'Tag', 'curve_Pol_text', ...\n\t\t\t'Style', 'text', ...\n\t\t\t'Units', 'normalized', ...\n\t\t\t'Position', [0.0602006688963211 0.0740740740740741 0.82943143812709 0.527777777777778], ...\n\t\t\t'FontSize', 10, ...\n\t\t\t'BackgroundColor', [0.839 0.91 0.851], ...\n\t\t\t'String', 'Curve Equation');\n\n\t\t% --- PUSHBUTTONS -------------------------------------\n\t\thandles.import_loadImg_pushbutton = uicontrol( ...\n\t\t\t'Parent', handles.import_uipanel, ...\n\t\t\t'Tag', 'import_loadImg_pushbutton', ...\n\t\t\t'UserData', zeros(1,0), ...\n\t\t\t'Style', 'pushbutton', ...\n\t\t\t'Units', 'normalized', ...\n\t\t\t'Position', [0.0735785953177258 0.669194186256364 0.247491638795987 0.25974025974026], ...\n\t\t\t'FontSize', 10, ...\n\t\t\t'String', 'Load Image', ...\n\t\t\t'TooltipString', 'Load curve image', ...\n\t\t\t'CData', zeros(1,0), ...\n\t\t\t'Callback', @import_loadImg_pushbutton_Callback);\n\n\t\thandles.import_getScaleFile_pushbutton = uicontrol( ...\n\t\t\t'Parent', handles.import_uipanel, ...\n\t\t\t'Tag', 'import_getScaleFile_pushbutton', ...\n\t\t\t'Style', 'pushbutton', ...\n\t\t\t'Units', 'normalized', ...\n\t\t\t'Position', [0.377926421404682 0.668831168831169 0.324414715719064 0.25974025974026], ...\n\t\t\t'FontSize', 10, ...\n\t\t\t'String', 'Get Scale File', ...\n\t\t\t'TooltipString', 'Get a previous scale file', ...\n\t\t\t'Enable', 'off', ...\n\t\t\t'Callback', @import_getScaleFile_pushbutton_Callback);\n\n\t\thandles.import_scale_pushbutton = uicontrol( ...\n\t\t\t'Parent', handles.import_uipanel, ...\n\t\t\t'Tag', 'import_scale_pushbutton', ...\n\t\t\t'Style', 'pushbutton', ...\n\t\t\t'Units', 'normalized', ...\n\t\t\t'Position', [0.0735785953177258 0.363999381061558 0.240802675585284 0.201298701298701], ...\n\t\t\t'FontSize', 10, ...\n\t\t\t'String', 'Set Scale', ...\n\t\t\t'TooltipString', 'Set image scale by marking points on axes and writing the difference between these points', ...\n\t\t\t'Enable', 'off', ...\n\t\t\t'Callback', @import_scale_pushbutton_Callback);\n\n\t\thandles.import_MarkRef_pushbutton = uicontrol( ...\n\t\t\t'Parent', handles.import_uipanel, ...\n\t\t\t'Tag', 'import_MarkRef_pushbutton', ...\n\t\t\t'Style', 'pushbutton', ...\n\t\t\t'Units', 'normalized', ...\n\t\t\t'Position', [0.0769230769230769 0.0977656148277906 0.471571906354515 0.201298701298701], ...\n\t\t\t'FontSize', 10, ...\n\t\t\t'String', 'Mark Reference Point', ...\n\t\t\t'TooltipString', 'set the C.S. by marking a point in the image. point value is set on the right', ...\n\t\t\t'Enable', 'off', ...\n\t\t\t'Callback', @import_MarkRef_pushbutton_Callback);\n\n\t\thandles.curve_markPoints_pushbutton = uicontrol( ...\n\t\t\t'Parent', handles.curve_uipanel, ...\n\t\t\t'Tag', 'curve_markPoints_pushbutton', ...\n\t\t\t'Style', 'pushbutton', ...\n\t\t\t'Units', 'normalized', ...\n\t\t\t'Position', [0.0635451505016723 0.675925925925926 0.404682274247492 0.305555555555555], ...\n\t\t\t'FontSize', 10, ...\n\t\t\t'String', 'Mark Curve Points', ...\n\t\t\t'TooltipString', 'Mark points on the curve', ...\n\t\t\t'Enable', 'off', ...\n\t\t\t'Callback', @curve_markPoints_pushbutton_Callback);\n\n\t\thandles.save_pushbutton = uicontrol( ...\n\t\t\t'Parent', handles.save_uipanel, ...\n\t\t\t'Tag', 'save_pushbutton', ...\n\t\t\t'Style', 'pushbutton', ...\n\t\t\t'Units', 'centimeters', ...\n\t\t\t'Position', [5.49915166666667 2.08862010416666 2.1414965625 0.846023333333334], ...\n\t\t\t'String', 'Save to mat', ...\n\t\t\t'TooltipString', 'Save results', ...\n\t\t\t'Enable', 'off', ...\n\t\t\t'Callback', @save_pushbutton_Callback);\n\n\t\thandles.save_excel_pushbutton = uicontrol( ...\n\t\t\t'Parent', handles.save_uipanel, ...\n\t\t\t'Tag', 'save_excel_pushbutton', ...\n\t\t\t'Style', 'pushbutton', ...\n\t\t\t'Units', 'centimeters', ...\n\t\t\t'Position', [5.49915166666667 1.16328208333333 2.1414965625 0.846023333333334], ...\n\t\t\t'String', 'Save to excel', ...\n\t\t\t'TooltipString', 'Save results', ...\n\t\t\t'Enable', 'off', ...\n\t\t\t'Callback', @save_excel_pushbutton_Callback);\n\n\t\thandles.save_ws_pushbutton = uicontrol( ...\n\t\t\t'Parent', handles.save_uipanel, ...\n\t\t\t'Tag', 'save_ws_pushbutton', ...\n\t\t\t'Style', 'pushbutton', ...\n\t\t\t'Units', 'centimeters', ...\n\t\t\t'Position', [5.49915166666667 0.237944062499997 2.1414965625 0.846023333333334], ...\n\t\t\t'String', 'Save to WS', ...\n\t\t\t'TooltipString', 'Save results', ...\n\t\t\t'Enable', 'off', ...\n\t\t\t'Callback', @save_ws_pushbutton_Callback);\n\n\t\t% --- EDIT TEXTS -------------------------------------\n\t\thandles.import_MarkRefX_edit = uicontrol( ...\n\t\t\t'Parent', handles.import_uipanel, ...\n\t\t\t'Tag', 'import_MarkRefX_edit', ...\n\t\t\t'Style', 'edit', ...\n\t\t\t'Units', 'normalized', ...\n\t\t\t'Position', [0.648829431438127 0.123739640801817 0.0869565217391304 0.155844155844156], ...\n\t\t\t'FontSize', 10, ...\n\t\t\t'BackgroundColor', [1 1 1], ...\n\t\t\t'String', '0', ...\n\t\t\t'TooltipString', 'Reference point X value', ...\n\t\t\t'Callback', @import_MarkRefX_edit_Callback, ...\n\t\t\t'CreateFcn', @import_MarkRefX_edit_CreateFcn);\n\n\t\thandles.import_MarkRefY_edit = uicontrol( ...\n\t\t\t'Parent', handles.import_uipanel, ...\n\t\t\t'Tag', 'import_MarkRefY_edit', ...\n\t\t\t'Style', 'edit', ...\n\t\t\t'Units', 'normalized', ...\n\t\t\t'Position', [0.749163879598662 0.123739640801817 0.0869565217391304 0.155844155844156], ...\n\t\t\t'FontSize', 10, ...\n\t\t\t'BackgroundColor', [1 1 1], ...\n\t\t\t'String', '0', ...\n\t\t\t'TooltipString', 'Reference point Y value', ...\n\t\t\t'Callback', @import_MarkRefY_edit_Callback, ...\n\t\t\t'CreateFcn', @import_MarkRefY_edit_CreateFcn);\n\n\t\thandles.curve_PolOrder_edit = uicontrol( ...\n\t\t\t'Parent', handles.curve_uipanel, ...\n\t\t\t'Tag', 'curve_PolOrder_edit', ...\n\t\t\t'Style', 'edit', ...\n\t\t\t'Units', 'normalized', ...\n\t\t\t'Position', [0.832775919732442 0.703703703703704 0.130434782608696 0.203703703703704], ...\n\t\t\t'FontSize', 10, ...\n\t\t\t'BackgroundColor', [1 1 1], ...\n\t\t\t'String', '3', ...\n\t\t\t'TooltipString', 'Polynom order', ...\n\t\t\t'Callback', @curve_PolOrder_edit_Callback, ...\n\t\t\t'CreateFcn', @curve_PolOrder_edit_CreateFcn);\n\n\t\thandles.save_fName_edit = uicontrol( ...\n\t\t\t'Parent', handles.save_uipanel, ...\n\t\t\t'Tag', 'save_fName_edit', ...\n\t\t\t'Style', 'edit', ...\n\t\t\t'Units', 'centimeters', ...\n\t\t\t'Position', [0.502326354166667 1.00465270833333 4.78531947916666 1.08396739583333], ...\n\t\t\t'FontSize', 10, ...\n\t\t\t'BackgroundColor', [1 1 1], ...\n\t\t\t'String', 'Curve', ...\n\t\t\t'TooltipString', 'Save file name', ...\n\t\t\t'Callback', @save_fName_edit_Callback, ...\n\t\t\t'CreateFcn', @save_fName_edit_CreateFcn);\n\n\n\tend\n\n%% ---------------------------------------------------------------------------\n\tfunction import_loadImg_pushbutton_Callback(hObject,evendata) %#ok\n \n [picName, dirNm] = uigetfile('*');\n if picName == 0\n return\n end\n \n if ~strcmp(dirNm, cd)\n picName = [dirNm picName];\n end\n img = imread(picName);\n \n handles.disp_fig = figure;\n \n imagesc([], [], flipdim(img,1));\n set(gca,'ydir','normal', 'XTick', [], 'YTick', []);\n \n % set(handles.disp_fig, 'Pointer', 'fullcrosshair')\n \n handles.disp_ax = gca;\n \n setappdata(handles.img2curve_figure, 'img', img);\n \n pushbutton_activate('import');\n\n\tend\n\n%% ---------------------------------------------------------------------------\n\tfunction import_getScaleFile_pushbutton_Callback(hObject,evendata) %#ok\n \n [fName, dirNm] = uigetfile('scale.mat');\n if fName == 0\n return\n end\n \n S = load([dirNm fName]);\n try\n setappdata(handles.img2curve_figure, 'scale', S.scale);\n setappdata(handles.img2curve_figure, 'oo', S.oo);\n setappdata(handles.img2curve_figure, 'ooVal', S.ooVal);\n \n plotImBackground;\n \n pushbutton_activate;\n catch\n errordlg('Previous scale file loading failed!', 'Load error');\n end\n\n\tend\n\n%% ---------------------------------------------------------------------------\n function import_scale_pushbutton_Callback(hObject,evendata) %#ok\n \n pushbutton_deactivate;\n \n scale = getAppD('scale', [1 1]);\n \n scale(1) = getAxisScale(1, scale(1));\n scale(2) = getAxisScale(2, scale(2));\n setappdata(handles.img2curve_figure, 'scale', scale);\n \n set(handles.import_xScale_text, 'String', {...\n ['X Scale 1:' num2str(scale(1), 3)],...\n ['Y Scale 1:' num2str(scale(2), 3)]});\n \n checkSaveScale;\n \n pushbutton_activate;\n \n end\n\n%% ---------------------------------------------------------------------------\n function import_MarkRef_pushbutton_Callback(hObject,evendata) %#ok\n \n pushbutton_deactivate;\n \n scale = getAppD('scale', [1 1]);\n oo = getAppD('oo',[]);\n ooVal = getAppD('ooVal', [0 0]);\n \n axes(handles.disp_ax);\n t = title(handles.disp_ax, ['Mark (' num2str(ooVal) ') point'],...\n 'FontSize', 16, 'Color', 'r');\n \n if isempty(oo)\n oo = ginput(1);\n else\n oo = ( ginput(1) ) ./scale + oo - ooVal ./ scale;\n end\n \n delete(t);\n \n pushbutton_activate;\n \n setappdata(handles.img2curve_figure, 'oo', oo);\n setOoVal;\n \n checkSaveScale;\n \n end\n\n%% ---------------------------------------------------------------------------\n function curve_markPoints_pushbutton_Callback(hObject,evendata) %#ok\n \n scale = [];\n oo = [];\n ooVal = [];\n names = {'scale' 'oo' 'ooVal'};\n for i = 1:length(names)\n if isappdata(handles.img2curve_figure, names{i})\n eval([names{i} ' = getappdata(handles.img2curve_figure, ''' names{i} ''');']);\n else\n errordlg('Set scale and oo first!', 'Error');\n return\n end\n end\n \n pushbutton_deactivate;\n \n axes(handles.disp_ax);\n \n tit = title(handles.disp_ax, {'Mark as many curve points as you want' 'Press Enter when done'},...\n 'FontSize', 16, 'Color', 'r');\n po = ginput;\n if isempty(po)\n try\n load('curvePoints.mat');\n catch %#ok<*CTCH>\n return\n end\n else\n save('curvePoints.mat', 'po');\n end\n \n setappdata(handles.img2curve_figure, 'po', po);\n \n calcPol;\n \n pushbutton_activate;\n \n end\n\n%% ---------------------------------------------------------------------------\n function save_pushbutton_Callback(hObject,evendata) %#ok\n \n po = getappdata(handles.img2curve_figure, 'po');\n oo = getappdata(handles.img2curve_figure, 'oo');\n ooVal = getappdata(handles.img2curve_figure, 'ooVal');\n scale = getappdata(handles.img2curve_figure, 'scale');\n pol = getappdata(handles.img2curve_figure, 'pol');\n img = getappdata(handles.img2curve_figure, 'img');\n \n fName = [get(handles.save_fName_edit, 'String') '.mat'];\n \n save(fName, 'po', 'oo', 'ooVal', 'scale', 'pol', 'img');\n \n msgbox([fName ' saved successfully!'], 'Save Fit', 'help');\n \n end\n\n%% ---------------------------------------------------------------------------\n function save_excel_pushbutton_Callback(hObject,evendata) %#ok\n \n po = getAppD('po', []);\n pol = getAppD('pol', []);\n \n if isempty(po) || isempty(pol)\n errordlg('Mark curve point first!', 'Excel export error');\n else\n fName = [get(handles.save_fName_edit, 'String') '.xls'];\n headStr = {'Polynomial fit:' '';\n poly2str(pol, 'x') '';\n 'Polynomial coefficients:' '';\n '' '';\n '' '';\n 'X' 'Y'};\n try\n xlswrite(fName, headStr, 'Sheet1', 'A1');\n xlswrite(fName, reshape(pol', 1, []) , 'Sheet1', 'A4');\n xlswrite(fName, po, 'Sheet1', 'A7');\n \n msgbox([fName ' saved successfully!'], 'Save Fit', 'help');\n catch\n errordlg({'Could not save to excel' 'Is excel file open?'}, 'Excel export error')\n end\n end\n \n end\n\n%% ---------------------------------------------------------------------------\n function save_ws_pushbutton_Callback(hObject,evendata) %#ok\n \n names = {'po', 'oo', 'ooVal', 'scale', 'pol', 'img'};\n for i = 1:length(names)\n assignin( 'base', names{i}, getappdata(handles.img2curve_figure, names{i}) );\n end\n \n msgbox('Results exported to WS successfully!', 'WS export Fit', 'help');\n \n end\n\n%% ---------------------------------------------------------------------------\n\tfunction import_MarkRefX_edit_Callback(hObject,evendata) %#ok\n\n\tend\n\n%% ---------------------------------------------------------------------------\n\tfunction import_MarkRefX_edit_CreateFcn(hObject,evendata) %#ok\n\n\tend\n\n%% ---------------------------------------------------------------------------\n\tfunction import_MarkRefY_edit_Callback(hObject,evendata) %#ok\n\n\tend\n\n%% ---------------------------------------------------------------------------\n\tfunction import_MarkRefY_edit_CreateFcn(hObject,evendata) %#ok\n\n\tend\n\n%% ---------------------------------------------------------------------------\n\tfunction curve_PolOrder_edit_Callback(hObject,evendata) %#ok\n\n\tend\n\n%% ---------------------------------------------------------------------------\n\tfunction curve_PolOrder_edit_CreateFcn(hObject,evendata) %#ok\n\n\tend\n\n%% ---------------------------------------------------------------------------\n\tfunction save_fName_edit_Callback(hObject,evendata) %#ok\n\n\tend\n\n%% ---------------------------------------------------------------------------\n\tfunction save_fName_edit_CreateFcn(hObject,evendata) %#ok\n\n end\n\n%% Service Functions\n\n function scale = getAxisScale(ax, scale)\n \n directionStr = {'x \\rightarrow' 'y \\uparrow'};\n \n axes(handles.disp_ax);\n t = title(handles.disp_ax,{ ['Get ' directionStr{ax} ' scale'], 'Mark 2 points, from small to large'}, ...\n 'FontSize', 16, 'Color', 'r');\n Po = ginput(2);\n if isempty(Po)\n % load('scale.mat')\n % scale = scale(ax);\n return\n else\n PoSize = ( Po(2,ax)-Po(1,ax) ) / scale;\n end\n \n Answer = inputdlg('Difference between the 2 points:', 'Get Scale');\n Me = str2num(Answer{1}); %#ok<*ST2NM>\n scale = Me/PoSize;\n delete(t);\n end\n\n\n function setOoVal\n \n ooVal(1) = str2num(get(handles.import_MarkRefX_edit, 'String'));\n ooVal(2) = str2num(get(handles.import_MarkRefY_edit, 'String'));\n setappdata(handles.img2curve_figure, 'ooVal', ooVal);\n end\n\n\n function checkSaveScale\n \n if isappdata(handles.img2curve_figure, 'scale') && isappdata(handles.img2curve_figure, 'oo')\n scale = getappdata(handles.img2curve_figure, 'scale'); %#ok<*NASGU>\n oo = getappdata(handles.img2curve_figure, 'oo');\n ooVal = getappdata(handles.img2curve_figure, 'ooVal');\n \n save('scale.mat', 'scale', 'oo', 'ooVal');\n \n plotImBackground;\n end\n \n end\n\n function pol = calcPol\n \n po = getappdata(handles.img2curve_figure, 'po');\n oo = getappdata(handles.img2curve_figure, 'oo');\n ooVal = getappdata(handles.img2curve_figure, 'ooVal');\n scale = getappdata(handles.img2curve_figure, 'scale');\n \n polOrder = str2num(get(handles.curve_PolOrder_edit, 'String'));\n pol = Fitting(po(:,1), po(:,2), polOrder+1);\n \n setappdata(handles.img2curve_figure, 'pol', pol);\n \n set(handles.curve_Pol_text, 'String', poly2str(pol, 'x'));\n showRes;\n \n end\n\n\n function showRes\n \n po = getappdata(handles.img2curve_figure, 'po');\n oo = getappdata(handles.img2curve_figure, 'oo');\n ooVal = getappdata(handles.img2curve_figure, 'ooVal');\n scale = getappdata(handles.img2curve_figure, 'scale');\n pol = getappdata(handles.img2curve_figure, 'pol');\n \n if isappdata(handles.img2curve_figure, 'lin')\n try %#ok\n lin = getappdata(handles.img2curve_figure, 'lin');\n delete(lin);\n end\n end\n \n x = po(:,1);\n y = po(:,2);\n yP = polyval( pol, po(:,1) );\n \n axes(handles.disp_ax);\n \n hold on\n % imagesc(scale(1), scale(2), img);\n lin = plot(x,y, 'o', x,yP,'--', 'linewidth', 2);\n hold off\n tit = title( poly2str(pol, 'x'), 'FontSize', 12, 'Color', 'k' );\n \n setappdata(handles.img2curve_figure, 'lin', lin);\n \n end\n\n function plotImBackground\n \n po = getappdata(handles.img2curve_figure, 'po');\n oo = getappdata(handles.img2curve_figure, 'oo');\n ooVal = getappdata(handles.img2curve_figure, 'ooVal');\n scale = getappdata(handles.img2curve_figure, 'scale');\n pol = getappdata(handles.img2curve_figure, 'pol');\n img = getappdata(handles.img2curve_figure, 'img');\n \n if isempty(ooVal)\n ooVal = [0 0];\n end\n \n oo = oo - ooVal./scale;\n \n minX = -1 * scale(1) * oo(1);\n maxX = scale(1) * (length(img(1,:,1)) - oo(1));\n \n minY = -1 * scale(2) * oo(2);\n maxY = scale(2) * (length(img(:,1,1)) - oo(2));\n \n imagesc([minX maxX], [minY maxY], flipdim(img,1), 'Parent', handles.disp_ax);\n set(handles.disp_ax,'ydir','normal');\n \n end\n\n function pushbutton_activate(indicat)\n \n pb = findobj(handles.img2curve_figure, 'Style', 'pushbutton');\n \n if nargin<1 % activate all\n set(pb, 'Enable', 'on');\n else\n pbb = [];\n for i = 1:length(pb)\n if strfind(get(pb(i), 'Tag'), indicat)\n pbb(end+1) = pb(i); %#ok\n end\n end\n set(pbb, 'Enable', 'on');\n end\n \n end\n\n function pushbutton_deactivate\n \n pb = findobj(handles.img2curve_figure, 'Style', 'pushbutton');\n \n set(pb, 'Enable', 'off');\n \n end\n\n function val = getAppD(name, def)\n \n if isappdata(handles.img2curve_figure, name)\n val = getappdata(handles.img2curve_figure, name);\n else\n val =def;\n end\n \n end\n\nend\n\n\nfunction Pol = Fitting(x, y, m)\n\nif nargin<3\n m = 2;\nend\n\nx = MakeColomVec(x);\ny = MakeColomVec(y);\n\nfor q=1:m\n A=[];\n for p=1:q\n A=[A x.^(p-1)]; %#ok\n end\n d(1:q,q) =A\\y; %#ok\n % plot(x, y, x,A*d(1:q,q),'--')\n % hold on\nend\n\nPol = d(1:q,q);\nPol = Pol(end:-1:1);\n\n function v = MakeColomVec(v)\n \n v = reshape(v, length(v), 1);\n end\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/41560-img2curve/img2curve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583270090337582, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.3976584583429551}}
{"text": "function clsts= getClusters(net, opts, clstFn, k, dbTrain, trainDescFn)\n \n if ~exist(clstFn, 'file')\n \n if ~exist(trainDescFn, 'file')\n \n simpleNnOpts= {'conserveMemory', true, 'mode', 'test'};\n \n if opts.useGPU\n net= relja_simplenn_move(net, 'gpu');\n end\n \n % ---------- extract training descriptors\n \n relja_display('Computing training descriptors');\n \n nTrain= 50000;\n nPerImage= 100;\n nIm= ceil(nTrain/nPerImage);\n \n rng(43);\n trainIDs= randsample(dbTrain.numImages, nIm);\n \n nTotal= 0;\n \n prog= tic;\n \n for iIm= 1:nIm\n relja_progress(iIm, nIm, 'extract train descs', prog);\n \n % --- extract descriptors\n \n % didn't want to complicate with batches here as it's only done once (per network and training set)\n \n im= vl_imreadjpeg({[dbTrain.dbPath, dbTrain.dbImageFns{iIm}]});\n im= im{1};\n \n % fix non-colour images\n if size(im,3)==1\n im= cat(3,im,im,im);\n end\n \n im(:,:,1)= im(:,:,1) - net.meta.normalization.averageImage(1,1,1);\n im(:,:,2)= im(:,:,2) - net.meta.normalization.averageImage(1,1,2);\n im(:,:,3)= im(:,:,3) - net.meta.normalization.averageImage(1,1,3);\n \n if opts.useGPU\n im= gpuArray(im);\n end\n \n res= vl_simplenn(net, im, [], [], simpleNnOpts{:});\n descs= gather(res(end).x);\n descs= reshape( descs, [], size(descs,3) )';\n \n % --- sample descriptors\n \n nThis= min( min(nPerImage, size(descs,2)), nTrain - nTotal );\n descs= descs(:, randsample( size(descs,2), nThis ) );\n \n if iIm==1\n trainDescs= zeros( size(descs,1), nTrain, 'single' );\n end\n \n trainDescs(:, nTotal+[1:nThis])= descs;\n nTotal= nTotal+nThis;\n end\n \n trainDescs= trainDescs(:, 1:nTotal);\n \n % move back to CPU addLayers() assumes it\n if opts.useGPU\n net= relja_simplenn_move(net, 'cpu');\n end\n \n save(trainDescFn, 'trainDescs');\n else\n relja_display('Loading training descriptors');\n load(trainDescFn, 'trainDescs');\n end\n \n % ---------- Cluster descriptors\n \n relja_display('Computing clusters');\n clsts= yael_kmeans(trainDescs, k, 'niter', 100, 'verbose', 0, 'seed', 43);\n clear trainDescs;\n \n save(clstFn, 'clsts');\n else\n relja_display('Loading clusters');\n load(clstFn, 'clsts');\n assert(size(clsts, 2)==k);\n end\n \nend\n", "meta": {"author": "Relja", "repo": "netvlad", "sha": "652dbe71aa45c691961ddd9f6cf902574e6bdc2f", "save_path": "github-repos/MATLAB/Relja-netvlad", "path": "github-repos/MATLAB/Relja-netvlad/netvlad-652dbe71aa45c691961ddd9f6cf902574e6bdc2f/getClusters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514777, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.39764504106854826}}
{"text": "function k = diagKernDiagCompute(kern, x)\n\n% DIAGKERNDIAGCOMPUTE Compute diagonal of DIAG kernel.\n% FORMAT\n% DESC computes the diagonal of the kernel matrix for the diagonal noise covariance function kernel given a design matrix of inputs.\n% ARG kern : the kernel structure for which the matrix is computed.\n% ARG x : input data matrix in the form of a design matrix.\n% RETURN k : a vector containing the diagonal of the kernel matrix\n% computed at the given points.\n%\n% SEEALSO : diagKernParamInit, kernDiagCompute, kernCreate, diagKernCompute\n%\n% COPYRIGHT : Neil D. Lawrence, 2011\n\n% KERN\n\n if size(x, 2)>1\n error('Diag kernel requires 1-dimensional input.')\n end\n trans = str2func([kern.trans, 'Transform']);\n k = kern.variance*trans(x, 'atox');\nend\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/diagKernDiagCompute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.39764503401806717}}
{"text": "function extent = imPhysicalExtent(img, varargin)\n%IMPHYSICALEXTENT Compute the physical extent of an image\n%\n% BOX = imPhysicalExtent(IMG)\n% Returns the physical extent of the image IMG, such that the display\n% will be contained within the extent. IMG can be either 2D or 3D image.\n%\n% BOX = imPhysicalExtent(IMG, SPACING)\n% Computes the extent by taking into account the resolution of the image.\n% The resolution is given in X-Y-Z order (ie., SPACING(1) corresponds to\n% the resolution of the second dimension of IMG).\n%\n% BOX = imPhysicalExtent(IMG, SPACING, ORIGIN)\n% Also takes into account the stack origin, i.e. the coordinates of the\n% first voxel expressed in user coordinates.\n% The origin is given in X-Y-Z order.\n%\n% BOX = imPhysicalExtent(IMG, 'spacing', SPACING, 'origin', ORIGIN)\n% Uses a syntax based on parameter name-value pairs.\n%\n% BOX = imPhysicalExtent(DIM, SPACING, ORIGIN)\n% Computes the physical extent based on the size of the stack. This\n% syntax can be used to avoid passing an array as parameter. DIM is given\n% in X-Y-Z order.\n%\n%\n% Example\n% % Compute physical extent of MRI Human head\n% metadata = analyze75info('brainMRI.hdr');\n% I = analyze75read(metadata);\n% box = imPhysicalExtent(I, [1 1 2.5])\n% box =\n% 0.5000 128.5000 0.5000 128.5000 -0.2500 67.2500\n%\n% See also\n% imSize\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2011-03-03, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2011 INRA - Cepia Software Platform.\n\n\n% size of image in each physical direction\nsz = imSize(img);\n% if length(dim) > 2\n% % compute size of the stack\n% sz = stackSize(img);\n% else\n% % the size of the stack is given as input\n% sz = img;\n% end\n\n% default spacing and origin (matlab display convention)\nnd = length(sz);\nsp = ones(1, nd);\nor = ones(1, nd);\n\n% parse origin and spacing of the stack\nif ~isempty(varargin)\n var = varargin{1};\n \n if isnumeric(var)\n % extract voxel spacing\n sp = var;\n \n if length(varargin) > 1\n % also extract voxel origin\n or = varargin{2};\n end\n \n elseif ischar(var)\n while length(varargin) > 2\n paramName = varargin{1};\n if strcmp(paramName, 'spacing')\n sp = varargin{2};\n \n elseif strcmp(paramName, 'origin')\n or = varargin{2};\n \n else\n error(['Unknown parameter: ' paramName]);\n end\n end\n end\nend\n\n% put extent in array\nextent = (([zeros(nd, 1) sz'] - .5).* [sp' sp'] + [or' or'])';\n\n% change array shape to get a single row\nextent = extent(:)';\n", "meta": {"author": "mattools", "repo": "matImage", "sha": "94d892c7beac0db32daadf2646ce37f58e894caf", "save_path": "github-repos/MATLAB/mattools-matImage", "path": "github-repos/MATLAB/mattools-matImage/matImage-94d892c7beac0db32daadf2646ce37f58e894caf/matImage/imMeasures/imPhysicalExtent.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.39764503401806717}}
{"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": "% drawcloud ... draw point cloud\n%\n% [fig] = drawcloud(X,fig,{color})\n%\n% X ... 3xn matrix containing the points\n% if X is 4xn only the first 3 rows are used\n% fig . figure handle\n% color color of plotting; defaults to blue\n%\n% fig . return the figure handle\n%\n% $Id: drawcloud.m,v 2.0 2003/06/19 12:07:02 svoboda Exp $\n\nfunction [fig] = drawcloud(X,fig,color)\nif nargin < 3\n color = 'b';\t% default color\nend\n\nfigure(fig), hold on\nplot3(X(1,:),X(2,:),X(3,:),[color,'o'])\n\n\nview([1,1,1]);\naxis('equal');\ngrid on\nrotate3d on\nfig=fig;\nreturn\n", "meta": {"author": "strawlab", "repo": "MultiCamSelfCal", "sha": "0a26c88c63d8513eab76553033a9a6fb15ba6575", "save_path": "github-repos/MATLAB/strawlab-MultiCamSelfCal", "path": "github-repos/MATLAB/strawlab-MultiCamSelfCal/MultiCamSelfCal-0a26c88c63d8513eab76553033a9a6fb15ba6575/MultiCamSelfCal/OutputFunctions/drawcloud.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.3976392844235306}}
{"text": "function msg = mhe_init()\n\ns = 'http://byu.apmonitor.com';\nb = 'mhe';\n\napm(s,b,'clear all');\n\n% load model and data\napm_load(s,b,'model.apm');\ncsv_load(s,b,'mhe.csv');\n\n% configure MV / CV\napm_info(s,b,'FV','Kp');\napm_info(s,b,'FV','tau');\napm_info(s,b,'FV','zeta');\napm_info(s,b,'FV','TC_ss');\napm_info(s,b,'MV','Q1');\napm_info(s,b,'CV','TC');\n\n% dynamic estimation\napm_option(s,b,'nlc.imode',5);\napm_option(s,b,'nlc.solver',3);\n\n% tune FV\napm_option(s,b,'Kp.dmax',0.05);\napm_option(s,b,'Kp.lower',0.3);\napm_option(s,b,'Kp.upper',0.6);\napm_option(s,b,'tau.dmax',2.0);\napm_option(s,b,'tau.lower',40.0);\napm_option(s,b,'tau.upper',60.0);\napm_option(s,b,'zeta.dmax',0.05);\napm_option(s,b,'zeta.lower',1.3);\napm_option(s,b,'zeta.upper',1.7);\napm_option(s,b,'TC_ss.dmax',1.0);\napm_option(s,b,'TC_ss.lower',22.0);\napm_option(s,b,'TC_ss.upper',25.0);\n% turn on FVs as degrees of freedom\napm_option(s,b,'Kp.status',1);\napm_option(s,b,'tau.status',1);\napm_option(s,b,'zeta.status',1);\napm_option(s,b,'TC_ss.status',1);\n\napm_option(s,b,'Kp.fstatus',0);\napm_option(s,b,'tau.fstatus',0);\napm_option(s,b,'zeta.fstatus',0);\napm_option(s,b,'TC_ss.fstatus',0);\n\n% read Q, don't let optimize use MV\napm_option(s,b,'Q1.status',0);\napm_option(s,b,'Q1.fstatus',1);\n% include CV in objective function\napm_option(s,b,'TC.status',1);\napm_option(s,b,'TC.fstatus',1);\n\n% web-viewer option, update every second\napm_option(s,b,'nlc.web_plot_freq',2);\n\nmsg = 'initialization complete';\n\nend", "meta": {"author": "APMonitor", "repo": "arduino", "sha": "f36e65a70dd7122d1829883899e40e56bf6c4279", "save_path": "github-repos/MATLAB/APMonitor-arduino", "path": "github-repos/MATLAB/APMonitor-arduino/arduino-f36e65a70dd7122d1829883899e40e56bf6c4279/5_Moving_Horizon_Estimation/2nd_order_linear/MATLAB/mhe_init.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.3976392803755817}}
{"text": "function f=loglikGaPExpWfix(x, varargin)\n% f=loglikGaP(x, varargin)\n% complete log likellihood of the GaP model \n% Vxt = varargin{1}; %data\n% sigpsf = varargin{2}; %std deviation of the PSF gaussian approx\n% alpha = varargin{3}; %parameters of the Gamma prior on the blinking\n% beta = varargin{4}; %parameters of the Gamma prior on the blinking\n% peval = varargin{5}; %parameters\n% x(1:end-2*peval.ncomp) is Hkt\n\n\nVxt = varargin{1}; %data\nsigpsf = varargin{2}; %std deviation of the PSF gaussian approx\nalpha = varargin{3}; %parameters of the Gamma prior on the blinking\nbeta = varargin{4}; %parameters of the Gamma prior on the blinking\npeval = varargin{5}; %parameters\n\n[Hkt_r, cx, cy, Wxk] = loglikGaPreadparamWfix(x,varargin);\nHkt=exp(Hkt_r); %nonnegativity constrains\n\n[Wxkbg,Hktbg]=addbg(Wxk, Hkt, peval.bg);\nP=Wxkbg*Hktbg; %current approximation\n\n%Poisson contribution\nt1=Vxt.*log(P) - P;\n%Gamma contribution\n% t2=(alpha-1)*log(Hkt)-1/beta*Hkt-alpha*log(beta)-log(gamma(alpha));\nt2=-1/beta*Hkt;\n\nf=sum(t1(:));%+sum(t2(:)));\nf=-f; %conjugate gradient is mimimizing!\nend", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/conjgradfunctions/loglikGaPExpWfix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.3975193296042883}}
{"text": "% Codes for CVPR-15 work `Face Alignment by Coarse-to-Fine Shape Searching'\n% Any question please contact Shizhan Zhu: zhshzhutah2@gmail.com\n% Released on July 25, 2015\n\nfunction currentPose = inferenceReg(images,model,Pr,level,regsInfo)\n\nm = length(images);\nn_pts = size(model{level}.tpt,2) / 2;\ntpt = model{max(1,level-1)}.tpt;\nmt = size(tpt,1);\n\n% 61. Sampling\nindex_inference = zeros(m,regsInfo.samplingTot(level));\ncurrentPose_inference = zeros(m,2*n_pts,regsInfo.samplingTot(level));\nfor i = 1:m\n if level > 1\n [~,tmp] = sort(Pr(i,:),'descend');\n index_inference(i,:) = tmp(1:regsInfo.samplingTot(level));\n else\n index_inference(i,:) = randSampleNoReplace(mt, regsInfo.samplingTot(level), Pr(i,:));\n end;\n for j = 1:regsInfo.samplingTot(level)\n currentPose_inference(i,:,j) = tpt(index_inference(i,j),:);\n end;\nend;\n\n% 62. Inference Iteration\nfeatInfo.scale = regsInfo.SIFTscale;\nfor iter = 1:regsInfo.iterTot(level)\n featOri_batch = extractSIFTs_toosimple_samples(images,currentPose_inference,iter,featInfo);\n for j = 1:regsInfo.samplingTot(level)\n currentPose_inference(:,:,j) = currentPose_inference(:,:,j) + ...\n (featOri_batch(:,:,j) - repmat(model{level}.reg{iter}.mu,m,1)) * model{level}.reg{iter}.A ...\n + repmat(model{level}.reg{iter}.b,m,1);\n end;\nend;\n\ncurrentPose = poseVoting(currentPose_inference,regsInfo.dominantIterTot(level));\n\nend\n\n", "meta": {"author": "zhusz", "repo": "CVPR15-CFSS", "sha": "11b8d0b28a4a3e954741a4dae2f114df7b644d4e", "save_path": "github-repos/MATLAB/zhusz-CVPR15-CFSS", "path": "github-repos/MATLAB/zhusz-CVPR15-CFSS/CVPR15-CFSS-11b8d0b28a4a3e954741a4dae2f114df7b644d4e/inferenceReg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624890918021, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.39744529768711057}}
{"text": "function [Pbest,Gbest] = GetBest(Archive,W,Z)\n% Update the pbest and gbest of each particle\n\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n %% Select the pbest\n AObj = Archive.objs - repmat(Z,length(Archive),1);\n NormW = sqrt(sum(W.^2,2))';\n d1 = AObj*W'./repmat(NormW,length(Archive),1);\n d2 = sqrt(repmat(sum(AObj.^2,2),1,size(W,1))-d1.^2);\n PBI = d1 + 5*d2;\n [~,p] = min(PBI,[],1);\n Pbest = Archive(p);\n \n %% Select the gbest\n Gbest = Archive(randi(size(Archive,1),1,size(W,1)));\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/MMOPSO/GetBest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3974452873898389}}
{"text": "function [vertices, faces] = freesurfer_read_surf(fname)\n\n% freesurfer_read_surf - FreeSurfer I/O function to read a surface file\n% \n% [vertices, faces] = freesurfer_read_surf(fname)\n% \n% Reads the vertex coordinates (mm) and face lists from a surface file.\n% \n% Surface files are stored as either triangulations or quadrangulations.\n% That is, for a triangulation, each face is defined by 3 vertices. For a\n% quadrangulation, each face is defined by 4 vertices. The rows of 'faces'\n% contain indices into the rows of 'vertices', the latter holds the XYZ\n% coordinates of each vertex.\n%\n% The freesurfer faces index the vertices in counter-clockwise order (when\n% viewed from the outside of the surface). This is consistent with a\n% right-hand rule. If we have vertices\n%\n% C B\n%\n%\n% A\n%\n% Then we can calculate an edge vector from A to B (ie, AB = B - A) and\n% another edge vector from A to C (ie, AC = C - A). If you form a \"gun\"\n% with your thumb and forefinger of the right hand, then align your thumb\n% with the AB vector and your forefinger with the AC vector, your palm is\n% facing out of the screen and extending your middle finger in the\n% orthogonal direction to the plane of the screen will give the outward\n% surface normal of the triangle ABC. (If you lookup \"triangle\" on\n% Wolfram's mathworld, you can see that AB is referred to as c and AC is\n% referred to as b.)\n%\n% However, if this surface is read into matlab, it will give INWARD surface\n% normals in the matlab patch command. For some reason, matlab is not\n% following the right hand rule. To get OUTWARD normals with the matlab\n% patch command, use faces(:,[1 3 2]) (see below).\n%\n% The vertex coordinates are in mm. The FreeSurfer coordinate\n% system for surfaces is quite simple, but relating to their MRI\n% cor-??? files is too confusing to explain here; see the FreeSurfer\n% homepage or google the documentation by Graham Wideman. For the\n% surfaces, at least, the origin is somewhere in the center of the\n% head, and the vertex XYZ coordinates are oriented such that +X is\n% right, +Y is anterior and +Z is superior (this is the\n% FreeSurfer RAS coordinate system).\n%\n% Note that reading the faces of a quad file can take a long\n% time due to their compact storage format. In this case, the return of\n% vertices can be faster if the face output variable is not specified; in\n% this case, the faces are not read.\n% \n% Try this to visualize the surface:\n% Hp = patch('vertices',vertices,'faces',faces(:,[1 3 2]),...\n% 'facecolor',[.5 .5 .5],'edgecolor','none')\n% camlight('headlight','infinite')\n% vertnormals = get(Hp,'vertexnormals');\n%\n% See also freesurfer_write_surf, freesurfer_read_curv,\n% freesurfer_read_wfile\n%\n\n% $Revision: 1.2 $ $Date: 2011/02/07 21:47:40 $\n\n% Copyright (C) 2000 Darren L. Weber\n\n% History: 08/2000, Darren.Weber_at_radiology.ucsf.edu\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nver = '$Revision: 1.2 $ $Date: 2011/02/07 21:47:40 $';\nfprintf('FREESURFER_READ_SURF [v %s]\\n',ver(11:15));\n\nif(nargin < 1)\n help freesurfer_read_surf;\n return;\nend\n\n%QUAD_FILE_MAGIC_NUMBER = (-1 & 0x00ffffff) ;\n%NEW_QUAD_FILE_MAGIC_NUMBER = (-3 & 0x00ffffff) ;\n\nTRIANGLE_FILE_MAGIC_NUMBER = 16777214;\nQUAD_FILE_MAGIC_NUMBER = 16777215;\n\n\n% open it as a big-endian file\nfid = fopen(fname, 'rb', 'b');\nif (fid < 0),\n str = sprintf('could not open surface file %s.', fname);\n error(str);\nend\n\nfprintf('...reading surface file: %s\\n', fname);\ntic;\n\nmagic = freesurfer_fread3(fid);\n\nif (magic == QUAD_FILE_MAGIC_NUMBER),\n Nvertices = freesurfer_fread3(fid);\n Nfaces = freesurfer_fread3(fid);\n fprintf('...reading %d quad file vertices\\n',Nvertices);\n vertices = fread(fid, Nvertices*3, 'int16') ./ 100 ; \n if (nargout > 1),\n fprintf('...reading %d quad file faces (please wait)\\n',Nfaces);\n faces = zeros(Nfaces,4);\n for iface = 1:Nfaces,\n for n=1:4,\n faces(iface,n) = freesurfer_fread3(fid) ;\n end\n if(~rem(iface, 10000)), fprintf(' %7.0f',iface); end\n if(~rem(iface,100000)), fprintf('\\n'); end\n end\n end\nelseif (magic == TRIANGLE_FILE_MAGIC_NUMBER),\n fprintf('...reading triangle file\\n');\n tline = fgets(fid); % read creation date text line\n tline = fgets(fid); % read info text line\n \n Nvertices = fread(fid, 1, 'int32'); % number of vertices\n Nfaces = fread(fid, 1, 'int32'); % number of faces\n \n % vertices are read in column format and reshaped below\n vertices = fread(fid, Nvertices*3, 'float32');\n \n % faces are read in column format and reshaped\n faces = fread(fid, Nfaces*3, 'int32');\n faces = reshape(faces, 3, Nfaces)';\nelse\n str = sprintf('unknown magic number in surface file %s.', fname);\n error(str);\nend\n\nvertices = reshape(vertices, 3, Nvertices)';\nfclose(fid);\n\nfprintf('...adding 1 to face indices for matlab compatibility.\\n');\nfaces = faces + 1;\n\nt=toc; fprintf('...done (%6.2f sec)\\n\\n',t);\n\nreturn\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/freesurfer_read_surf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3973971254124779}}
{"text": "%GETDEFAULTNEWCAMERAMATRIX Returns the default new camera matrix\n%\n% newCameraMatrix = cv.getDefaultNewCameraMatrix(cameraMatrix)\n% [...] = cv.getDefaultNewCameraMatrix(..., 'OptionName',optionValue, ...)\n%\n% ## Input\n% * __cameraMatrix__ Input camera matrix, a 3x3 double matrix.\n%\n% ## Output\n% * __newCameraMatrix__ Output camera matrix, same size and type as input.\n%\n% ## Options\n% * __ImgSize__ Camera view image size in pixels `[w,h]`. Default [0,0]\n% * __CenterPrincipalPoint__ Location of the principal point in the new camera\n% matrix. The parameter indicates whether this location should be at the\n% image center or not. default false\n%\n% The function returns the camera matrix that is either an exact copy of the\n% input `cameraMatrix` (when `CenterPrinicipalPoint=false`), or the modified\n% one (when `CenterPrincipalPoint=true`).\n%\n% In the latter case, the new camera matrix will be:\n%\n% [ fx, 0, (ImgSize(1)-1)*0.5 ;\n% 0, fy, (ImgSize(2)-1)*0.5 ;\n% 0, 0, 1 ]\n%\n% where `fx` and `fy` are (0,0) and (1,1) elements of `cameraMatrix`,\n% respectively.\n%\n% By default, the undistortion functions in OpenCV (see cv.undistort,\n% cv.initUndistortRectifyMap) do not move the principal point. However, when\n% you work with stereo, it is important to move the principal points in both\n% views to the same y-coordinate (which is required by most of stereo\n% correspondence algorithms), and may be to the same x-coordinate too. So, you\n% can form the new camera matrix for each view where the principal points are\n% located at the center.\n%\n% See also: cv.undistort, cv.initUndistortRectifyMap,\n% cv.getOptimalNewCameraMatrix\n%\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/+cv/getDefaultNewCameraMatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.39738825822417506}}
{"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": "function plotRelativeAmps(view)\n%\n% plotAmps(view)\n% \n% Bar plot of the amplitudes for each scan, averaging across\n% all pixels (in all slices) in the current ROI.\n% \n% gmb 5/25/98\n\n% Compute means across scans, for all pixels in the\n% currently selected ROI.\n[meanAmps,meanPhs] = vectorMeans(view);\n\nselectGraphWin\n\n% Header\nROIname = view.ROIs(view.selectedROI).name;\nheaderStr = ['Mean of amplitudes, ROI ',ROIname];\nset(gcf,'Name',headerStr);\n\n% Plot the bar graph\nclf\nfontSize = 14;\nmybar(meanAmps);\nxlabel('Scan','FontSize',fontSize);\nylabel('Mean Amplitude','FontSize',fontSize);\nylim =get(gca,'YLim');\nset(gca,'YLim',ylim*1.1);\nset(gca,'FontSize',fontSize);\n\n% Save the data in gca('UserData')\ndata.y = meanAmps;\nset(gca,'UserData',data);\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/Plots/plotRelAmps.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6791786991753931, "lm_q2_score": 0.5851011542032313, "lm_q1q2_score": 0.3973882407977717}}
{"text": "function h = times(f, g)\n%.* Times of two BALLFUNV objects. \n% F.*G if F is a BALLFUNV and G is double returns the BALLFUNV after\n% componentwise multiplication.\n%\n% F.*G if F is a BALLFUNV and G is a BALLFUNV returns the BALLFUNV\n% after multiplication of F by each component of G.\n% \n% See also MTIMES.\n\n% Copyright 2019 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nif isempty( f ) || isempty(g)\n h = ballfunv();\n return\nend\n\nfIsBallfun = isa(f, 'ballfun');\ngIsBallfun = isa(g, 'ballfun');\n\nif fIsBallfun\n G = g.comp;\n h = [f.*G{1} ; f.*G{2} ; f.*G{3}];\nelseif gIsBallfun\n F = f.comp;\n h = [F{1}.*g ; F{2}.*g ; F{3}.*g];\nelse\n F = f.comp;\n G = g.comp;\n h = [F{1}.*G{1} ; F{2}.*G{2} ; F{3}.*G{3}];\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/@ballfunv/times.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3973882407977716}}
{"text": "function f = times(f, g, varargin)\n%.* CLASSICFUN multiplication.\n% F.*G multiplies CLASSICFUN objects F and G or a CLASSICFUN by a scalar if\n% either F or G is a scalar.\n%\n% If F is an array-valued CLASSICFUN, then F.*C is supported if C is a row\n% vector of doubles with the same number of columns as F. Similarly if F if a\n% row vector of doubles and C is an array-valued CLASSICFUN\n%\n% If F and G are both CLASSICFUN objects, they are assumed to have the same\n% domain and, if they are array-valued, the same number of columns. The\n% method gives no warning if their domains don't agree, but the output of the\n% method will be meaningless.\n%\n% See also MTIMES, RDIVIDE.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nif ( isempty(f) || isempty(g) ) % CLASSICFUN * [] = []\n \n % Return empty:\n f = []; \n \nelseif ( ~isa(f, 'classicfun') ) % double * CLASSICFUN\n \n % If f is not a CLASSICFUN, g must be. Call ONEFUN/TIMES():\n g.onefun = times(f, g.onefun, varargin{:});\n % Swap arguments for output variable:\n f = g;\n \nelseif ( isa(g, 'classicfun')) % CLASSICFUN * CLASSICFUN\n \n % Multiply the ONEFUN objects of f and g together.\n f.onefun = times(f.onefun, g.onefun, varargin{:});\n \nelseif ( isa(g, 'double') ) % CLASSICFUN * double\n \n % Multiply the ONEFUN of f with g.\n f.onefun = times(f.onefun, g, varargin{:});\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/@classicfun/times.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3973882407977716}}
{"text": "function [x,y]=selectPolygon()\n% function [x,y]=selectPolygon()\n% OUTPUT: x,y - xy coordinates of vertices of selected polygon in figure\n% NOTE: The coord vectors are set up so that the last and first entries\n% are the same\n% PURPOSE:\n% Function to select a polygonal region in the current figure\n% and return the coordinates of the vertices (x,y)\n% USAGE:\n% - Left click to select point\n% - ESC to undo\n% - Right click to end and finish loop\n\n% Author: Ranjith Unnikrishnan\n%* Carnegie Mellon University, Vision and Mobile Robots Laboratory *\n%* THE MATERIAL EMBODIED IN THIS SOFTWARE IS PROVIDED TO YOU \"AS-IS\" *\n%* AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE, *\n%* INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR *\n%* FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL CARNEGIE MELLON *\n%* UNIVERSITY BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT, *\n%* SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY *\n%* KIND, OR ANY DAMAGES WHATSOEVER, INCLUDING WITHOUT LIMITATION, *\n%* LOSS OF PROFIT, LOSS OF USE, SAVINGS OR REVENUE, OR THE CLAIMS OF *\n%* THIRD PARTIES, WHETHER OR NOT CARNEGIE MELLON UNIVERSITY HAS BEEN *\n%* ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON *\n%* ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE *\n%* POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE. *\n%\n\nx=[];\ny=[];\ndone=0;\nn_selected=0;\ncrosses_h=1234.567; % some arbit number\nfirst=1;\nxlabel('left mouse=select, ESC=undo last selection, right mouse=finish');\n\nwhile (done==0)\n [xc,yc,button]=ginput(1);\n \n switch (button)\n case 1 % left button\n % Select point\n fprintf(1,'Selected point (%.3f,%.3f)\\n',xc,yc);\n x=[x;xc];\n y=[y;yc];\n n_selected=n_selected+1;\n case 27 % ESC key\n % Undo last point\n if(n_selected > 0)\n fprintf(1,'Deleted last point\\n');\n x(end)=[];\n y(end)=[];\n n_selected=n_selected-1;\n end\n case 3 % Right mouse button\n fprintf(1,'Ending\\n');\n done=1;\n if(length(x)>0)\n % Terminate\n x=[x;x(1)];\n y=[y;y(1)];\n end\n otherwise\n end\n \n if(ishandle(crosses_h)) \n %fprintf(1,'crosses_h is a handle\\n');\n delete(crosses_h);\n end\n\n hold on;\n if(length(x)>0)\n crosses_h=plot([x;x(1)],[y;y(1)],'wo-',...\n 'markersize',6,'linewidth',2);\n end\n hold off;\nend \n \n\n", "meta": {"author": "zhixy", "repo": "Laser-Camera-Calibration-Toolbox", "sha": "f0bd1b984c51dea79840c344c1fec8cb3d088730", "save_path": "github-repos/MATLAB/zhixy-Laser-Camera-Calibration-Toolbox", "path": "github-repos/MATLAB/zhixy-Laser-Camera-Calibration-Toolbox/Laser-Camera-Calibration-Toolbox-f0bd1b984c51dea79840c344c1fec8cb3d088730/src/selectPolygon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011397337391, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.3973882271708845}}
{"text": "function logLoss = prtEvalLogLoss(classifier,dataSet,nFolds)\n% prtEvalLogLoss Calculate log-loss after applying classifier to dataSet\n% \n% logLoss = prtEvalLogLoss(prtClassifier, prtDataSet) returns the\n% log-Loss for prtDataSet when classified by prtClassifier. prtDataSet\n% must be a labeled, prtDataSetStandard object. prtClassifier must be a\n% prtClass object.\n%\n% logLoss = prtEvalLogLoss(prtClassifier, prtDataSet, nFolds) returns\n% the log-Loss of prtDataSet when classified by prtClassifier with K-fold\n% cross-validation. prtDataSet must be a labeled, prtDataSetStandard\n% object. prtClassifier must be a prtClass object. nFolds is the number\n% of folds in the K-fold cross-validation.\n%\n% logLoss = prtEvalLogLoss(prtClassifier, prtDataSet, xValInds) same as\n% above, but use crossValidation with specified indices instead of random\n% folds.\n%\n% Note: since a lower log-loss is better, if log-loss is used in\n% feature selection, for example, you should optimize over the *negative*\n% log-loss.\n% \n% See the help for prtScoreLogLoss for more information.\n%\n% Example:\n% dataSet = prtDataGenSpiral;\n% classifier = prtClassDlrt;\n% ll = prtEvalLogLoss(classifier, dataSet)\n%\n% See Also: prtScoreLogLoss, prtEvalPdAtPf, prtEvalPfAtPd, prtEvalAuc, \n% prtEvalMinCost, prtEvalPercentCorrect\n\n\n\n\n\n\nif nargin < 3 || isempty(nFolds)\n nFolds = 1;\nend\nresults = prtUtilEvalParseAndRun(classifier,dataSet,nFolds);\nlogLoss = prtScoreLogLoss(results);\n", "meta": {"author": "covartech", "repo": "PRT", "sha": "4305e612af048e7dbf3d9392efc7436db125b1fc", "save_path": "github-repos/MATLAB/covartech-PRT", "path": "github-repos/MATLAB/covartech-PRT/PRT-4305e612af048e7dbf3d9392efc7436db125b1fc/eval/prtEvalLogLoss.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%\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": "function []=plot_dramapB(vResults)\n% --------------------------------------------\n% Plot Mc map on topography\n%\n% Incoming variables:\n% vResults: Necessarily includes vResults.mPolygon, vResults.mValueGrid, vResults.fSpacingHorizontal\n%\n% Author: J. Woessner, woessner@seismo.ifg.ethz.ch\n% last update: 27.02.03\n\n% get tbase.bin values\n[tmap,tmapleg] = tbase(3);\n\n% Construct a map graticule mesh for surface object display\n[lat,lon] = meshgrat(tmap,tmapleg);\n\n% Get coordinates from calculated Mc values, set up matrices\nvX=min(vResults.mPolygon(:,1)):vResults.fSpacingHorizontal:max(vResults.mPolygon(:,1));\nvY=min(vResults.mPolygon(:,2)):vResults.fSpacingHorizontal:max(vResults.mPolygon(:,2));\n[X , Y] = meshgrid(vX,vY);\n\n% % Set values of Mc to NaN\n vSel = find(vResults.mValueGrid(:,9)> 2.2);\n vResults.mValueGrid(vSel,9) = NaN;\n\n% Reshape\nmBvalues=reshape(vResults.mValueGrid(:,9),length(vY),length(vX));\n\n\n% Interpolate Values\nmBGrid = interp2(X,Y,mBvalues,lon,lat);\n\n% Create figure\nexfig=figure_exists('b-value worldmap',0);\nif exfig==0\n ui=figure_w_normalized_uicontrolunits( 'Name','b-value worldmap',...\n 'NumberTitle','off');\n figure_w_normalized_uicontrolunits(ui)\nend\n\nclf\nhold on;\naxis off;\naxesm('MapProjection','robinson')\n\n% Magic coloring\nmi = min(min(mBGrid));\nl = isnan(mBGrid);\nmBGrid(l) = mi-10;\nll = tmap < 0 & mBGrid < 0;\nmBGrid(ll) = mBGrid(ll)*0 + 10;\nhMap=meshm(mBGrid,tmapleg,size(tmap),tmap);\n\ndaspectm('m',20);\ntightmap\nview([0 90])\ncamlight; lighting phong\nset(gca,'projection','perspective');\n\nj = jet(60000);\nj = j(30000:60000,:);\n%j = winter(80000);\n%j = flipud(j);\nj = [ [ 0.9 0.9 0.9 ] ; j; [ 0.5 0.5 0.5] ];\n\n%caxis([ min(min(mBvalues)) max(max(mBvalues)) ]);\n%Harvard 0-70km\n%caxis([0.6 2.2])\n% ISC 0-70km\ncaxis([ 0.5 2]);\ncolormap(j); brighten(0.1);\n\naxis off; set(gcf,'color','k')\n\nsetm(gca,'ffacecolor','k')\nsetm(gca,'fedgecolor','w','flinewidth',1);\n\nsetm(gca,'mlabellocation',60)\nsetm(gca,'meridianlabel','on')\nsetm(gca,'plabellocation',25)\nsetm(gca,'parallellabel','on')\nsetm(gca,'Fontcolor','w','FontSize',10,'Fontweight','bold','Fontname','times','Labelunits','degrees')\nsetm(gca,'Labelformat','none')\nsetm(gca,'Grid','on')\nsetm(gca,'GLineStyle','-')\n\nh5 = colorbar;\n% Harvard 0-70km\n% set(h5,'position',[0.82 0.35 0.01 0.3],'TickDir','out','Ycolor','w','Xcolor','w',...\n% 'Fontweight','bold','FontSize',10,'YTick',[0.6 1 1.4 1.8 2.2] );\n% ISC 0-70km\nset(h5,'position',[0.82 0.35 0.01 0.3],'TickDir','out','Ycolor','w','Xcolor','w',...\n 'Fontweight','bold','FontSize',10,'Ytick',[0.5 1 1.5 2]);\n\nset(gcf,'Inverthardcopy','off');\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/Scriptlab/plot_dramapB.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.39731588687440994}}
{"text": "function K = sdlfmvXsdlfmvKernCompute(sdlfmvKern1, sdlfmvKern2, t1, t2, covIC)\n\n% SDLFMVXSDLFMVKERNCOMPUTE Compute a cross kernel between two SDLFMV kernels.\n% FORMAT\n% DESC computes cross kernel terms between the velocity of two switching \n% dynamical LFM kernels for the multiple output kernel.\n% ARG sdlfmvKern1 : the kernel structure associated with the velocity of the \n% first SDLFM kernel.\n% ARG sdlfmvKern2 : the kernel structure associated with the velocity of the \n% second SDLFM kernel.\n% ARG t : inputs for which kernel is to be computed.\n% ARG covIC : covariance for the initial conditions\n% RETURN K : block of values from kernel matrix.\n%\n% FORMAT\n% DESC computes cross kernel terms between the velocity of two SDLFM kernels \n% for the multiple output kernel.\n% ARG sdlfmvKern1 : the kernel structure associated with the velocity of \n% the first SDLFM kernel.\n% ARG sdlfmvKern2 : the kernel structure associated with the velocity of \n% the second SDLFM 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 covIC : covariance for the initial conditions\n% RETURN K : block of values from kernel matrix.\n%\n% SEEALSO : sdlfmvKernParamInit, sdlfmvKernCompute, sdlfmKernParamInit\n%\n% COPYRIGHT : Mauricio A. Alvarez, 2010\n\n% KERN\n\nif nargin < 4\n t2 = t1;\nend\n\nK = sdlfmXsdlfmKernCompute(sdlfmvKern1, sdlfmvKern2, t1, t2, covIC, 'VelVel');\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/sdlfmvXsdlfmvKernCompute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.39731588064982337}}
{"text": "classdef AreaColumn < DesignVariable\n \n properties (Access = public)\n \n end\n \n properties (Access = private)\n \n end\n \n methods (Access = public)\n \n function obj = AreaColumn(cParams)\n obj.init(cParams);\n obj.type = 'AreaColumn';\n obj.createInitialValue();\n end\n\n function A = getColumnArea(obj)\n x = obj.value;\n N = obj.mesh.nelem;\n A = x(1:N,1);\n end\n\n function V = computeVolum(obj)\n N = obj.mesh.nelem;\n A = obj.getColumnArea();\n V = (1/N)*sum(A);\n end\n \n function gamma = getFirstEigenMode(obj)\n x = obj.value;\n N = obj.mesh.nelem;\n gamma = x(N+1); \n end\n\n function v = getVariablesToPlot(obj)\n v{1} = obj.value;\n end \n\n function norm = computeL2normIncrement(obj)\n norm = 0;\n end\n \n end\n \n methods (Access = protected)\n \n function init(obj,cParams)\n obj.mesh = cParams.mesh;\n end\n \n function createInitialValue(obj)\n N = obj.mesh.nelem;\n x0 = 1*rand(N+1,1);%ones(N+1,1); \n obj.update(x0); \n end\n end\n\nend", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/Topology Optimization/DesignVariable/AreaColumn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.66192288918838, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.3972784128187483}}
{"text": "function test_example_megrealign\n\n% MEM 6gb\n% WALLTIME 00:10:00\n\n%\n%% Interpolating data from the CTF151 to the CTF275 sensor array using megrealign\n%\n% the two example files with the 151 and 275 channel CTF specifications are available from\n% ftp://ftp.fieldtriptoolbox.org/pub/fieldtrip/example/megrealign/\n\ngrad151 = ft_read_sens(dccnpath('/home/common/matlab/fieldtrip/data/ftp/example/megrealign/ctf151.mat'));\ngrad275 = ft_read_sens(dccnpath('/home/common/matlab/fieldtrip/data/ftp/example/megrealign/ctf275.mat'));\n\nvol = [];\nvol.r = 12;\nvol.o = [0 0 4];\n\n% in this example the dipole is carefully positioned on the same depth as\n% where the dipole layer for the interpolation will be located. The center\n% of the head is at [0 0 4], the radius is 12 cm, and the dipole layer that is\n% specified in ft_megrealign is 2.5 cm shifted inward from the head surface\ncfg = [];\ncfg.dip.pos = [0 0 13.5]; % 4 + 12 - 2.5\ncfg.dip.frequency = 1;\ncfg.headmodel = vol;\ncfg.grad = grad151;\ndata151 = ft_dipolesimulation(cfg);\ncfg.grad = grad275;\ndata275 = ft_dipolesimulation(cfg);\n\ncfg = [];\navg151 = ft_timelockanalysis(cfg, data151);\navg275 = ft_timelockanalysis(cfg, data275);\n\n% here I'll not only realign the 151 channel MEG data to the 275 channel and\n% vice versa, but also apply the ft_megrealign function from 151 to 151. In the\n% realignment the signal will be slightly distorted as a comparison of avg151_151\n% to avg151 would show.\ncfg = [];\ncfg.inwardshift = 3;\ncfg.headmodel = vol;\ncfg.template{1} = grad151; avg151_151 = ft_timelockanalysis([], ft_megrealign(cfg, avg151));\ncfg.template{1} = grad275; avg151_275 = ft_timelockanalysis([], ft_megrealign(cfg, avg151));\ncfg.template{1} = grad151; avg275_151 = ft_timelockanalysis([], ft_megrealign(cfg, avg275));\ncfg.template{1} = grad275; avg275_275 = ft_timelockanalysis([], ft_megrealign(cfg, avg275));\n\n% plot the realigned datasets\ncfg = [];\nfigure; ft_multiplotER(cfg, avg151_151);\ntitle('Interpolated from 151 to 151');\norient portrait; %print -dpng -r300 avg151_151.png\n\n%\nfigure; ft_multiplotER(cfg, avg151_275);\ntitle('Interpolated from 151 to 151');\norient portrait; %print -dpng -r300 avg151_275.png\n\n%\nfigure; ft_multiplotER(cfg, avg275_151);\ntitle('Interpolated from 151 to 151');\norient portrait; %print -dpng -r300 avg275_151.png\n\n%\nfigure; ft_multiplotER(cfg, avg275_275);\ntitle('Interpolated from 151 to 151');\norient portrait; %print -dpng -r300 avg275_275.png\n\n%\n% now plot them together\ncfg = [];\nfigure; ft_multiplotER(cfg, avg151, avg151_151, avg275_151);\norient portrait; %print -dpng -r300 compare151.png\n\n%\nfigure; ft_multiplotER(cfg, avg275, avg275_275, avg151_275);\norient portrait; %print -dpng -r300 compare275.png\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/test/test_example_megrealign20220113.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.66192288918838, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.3972784128187483}}
{"text": "function dynamics = dynamicsTest(type);\n\n% DYNAMICSTEST Run some tests on the specified dynamics model.\n\n% FGPLVM\n\ntype = [type 'Dynamics'];\nX = randn(10, 2);\nmodel = modelCreate(type, 2, 2, X);\n\n% Set the parameters randomly.\nparams = modelExtractParam(model);\nparams = randn(size(params))./sqrt(randn(size(params)).^2);\nmodel = modelExpandParam(model, params);\n\nepsilon = 1e-6;\nparams = modelExtractParam(model);\nif ~isempty(params)\n origParams = params;\n for i = 1:length(params);\n params = origParams;\n params(i) = origParams(i) + epsilon;\n model = modelExpandParam(model, params);\n Lplus(i) = modelLogLikelihood(model);\n params(i) = origParams(i) - epsilon;\n model = modelExpandParam(model, params);\n Lminus(i) = modelLogLikelihood(model);\n end\n params = origParams;\n model = modelExpandParam(model, params);\n \n gLDiff = .5*(Lplus - Lminus)/epsilon;\n g = modelGradientParam(model);\n nameBase = 'Parameter ';\n for i = 1:length(params)\n names{i} = [nameBase num2str(i)];\n end\n paramMaxDiff = max(max(abs(gLDiff-g)));\n if paramMaxDiff > 2*epsilon\n l = 0;\n for i = 1:length(names)\n if l < length(names{i})\n l = length(names{i});\n end\n end\n \n fprintf([char(repmat(32, 1, l)) '\\tanalytic diffs delta\\n']);\n for i = 1:length(names)\n spaceLen = l - length(names{i});\n space = char(repmat(32, 1, spaceLen));\n fprintf([space names{i} ':\\t%4.6f\\t%4.6f\\t%4.6f\\n'], ...\n g(i), gLDiff(i), gLDiff(i) - g(i));\n end\n end\nend\nLplus = zeros(size(X));\nLminus = zeros(size(X));\norigX = X;\nepsilon = 0.001;\nfor i = 1:size(X, 1)\n for j = 1:size(X, 2)\n X = origX;\n X(i, j) = origX(i, j) + epsilon;\n model = modelSetLatentValues(model, X);\n params = modelExtractParam(model);\n model = modelExpandParam(model, params);\n Lplus(i, j) = modelLogLikelihood(model);\n X(i, j) = origX(i, j) - epsilon;\n model = modelSetLatentValues(model, X);\n params = modelExtractParam(model);\n model = modelExpandParam(model, params);\n Lminus(i, j) = modelLogLikelihood(model);\n end\nend\nX = origX;\nmodel = modelSetLatentValues(model, X);\ngXDiff = .5*(Lplus - Lminus)/epsilon;\ng = modelLatentGradients(model);\nXMaxDiff = max(max(abs(g-gXDiff)));\nfprintf('X max diff: %2.6f.\\n', XMaxDiff)\nif XMaxDiff > 1e-6\n disp(g)\n disp(gXDiff)\n disp(g - gXDiff);\nend\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/fgplvm/dynamicsTest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.39727840481320437}}
{"text": "function [model] = tapas_linear_model(model, pars)\n%% Define the model.\n%\n% aponteeduardo@gmail.com\n% copyright (C) 2016\n%\n\nmodel = struct('graph', []);\nmodel.graph = cell(4, 1);\n\nfor i = 1:4\n model.graph{i} = struct('llh', [], 'htheta', []);\nend\n\nmodel.graph{1}.llh = @tapas_linear_llh;\nmodel.graph{2}.llh = @tapas_linear_hier_llh;\nmodel.graph{3}.llh = @tapas_linear_hier_llh;\nmodel.graph{4}.llh = [];\n\nmodel.graph{1}.htheta = struct('pe', 0.5, 'T', pars.T);\nmodel.graph{2}.htheta = struct('pe', 0.5, 'T', ones(size(pars.T)));\nmodel.graph{3}.htheta = struct('pe', 0.5, 'T', ones(size(pars.T)));\n\n% The last level is a dummy used to store the hyperpriors.\n\nmodel.graph{4}.htheta = struct('y', [], 'u', []);\n\n\nend\n\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/tools/ti/linear/tapas_linear_model.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.661922862511608, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.39727839680766025}}
{"text": "classdef AvePooling3D < dagnn.Filter\n properties\n method = 'avg'\n poolSize = [1 1 1]\n end\n\n methods\n function outputs = forward(obj, inputs, params)\n \n sz = size(inputs{1}); if numel(sz) < 4, sz(4) = 1; end \n nFrames = obj.poolSize(3) ;\n\n inputs{1} = reshape(inputs{1}, sz(1), sz(2), sz(3), nFrames, sz(4) / nFrames ) ; \n inputs{1} = permute(inputs{1}, [1 2 4 3 5]);\n sz_in = size(inputs{1});\n outputs{1} = mean(inputs{1},1);\n outputs{1} = mean(outputs{1},2);\n outputs{1} = mean(outputs{1},3);\n outputs{1} = permute(outputs{1}, [1 2 4 5 3]);\n \n% [outputs{1}, ~] = mex_maxpool3d(inputs{1},...\n% 'pool',obj.poolSize, 'stride', obj.stride, 'pad', obj.pad);\n% \n% outputs{1} = permute(outputs{1}, [1 2 4 3 5]);\n% sz_out = size(outputs{1});\n% if numel(sz_out) < 4, sz_out(4) = 1; end % fixes the case of time being pooled \n% \t nFrames = sz_out(4); % reset nframes\n% obj.net.meta.curNumFrames(obj.layerIndex) = nFrames ;\n% if numel(sz_out) < 5, sz_out(5) = 1; end % fixes the case of single batch \n% \n% outputs{1} = reshape(outputs{1}, sz_out(1), sz_out(2), sz_out(3), nFrames*sz_out(5) ) ; \n end\n\n function [derInputs, derParams] = backward(obj, inputs, params, derOutputs)\n % currently doing forward and backward due to idx\n sz = size(inputs{1}); if numel(sz) < 4, sz(4) = 1; end \n nFrames = obj.poolSize(3) ;\n inputs{1} = reshape(inputs{1}, sz(1), sz(2), sz(3), nFrames, sz(4) / nFrames ) ; \n inputs{1} = permute(inputs{1}, [1 2 3 5 4]);\n sz_in = size(inputs{1});\n for i=1:nFrames\n derInputs{1}(:,:,:,:,i) = vl_nnpool(inputs{1}(:,:,:,:,i), [sz(1),sz(2)], derOutputs{1}(:,:,:,:), ...\n 'pad', [0,0,0,0], ...\n 'stride', [1,1], ...\n 'method', 'avg') ;\n end\n derInputs{1} = reshape(derInputs{1}, sz(1), sz(2), sz(3),sz(4)) ;\n% nFramesIn = sz(4) / obj.net.meta.curBatchSize ;\n\n% inputs{1} = reshape(inputs{1}, sz(1), sz(2), sz(3), nFramesIn, sz(4) / nFramesIn ) ;\n% inputs{1} = permute(inputs{1}, [1 2 4 3 5]);\n% sz_in = size(inputs{1});\n% [~, idx] = mex_maxpool3d(inputs{1},...\n% 'pool',obj.poolSize, 'stride', obj.stride, 'pad', obj.pad);\n% \n% sz = size(derOutputs{1}); if numel(sz) < 4, sz(4) = 1; end \n% nFrames = sz(4) / obj.net.meta.curBatchSize ;\n% \n% \n% derOutputs{1} = reshape(derOutputs{1}, sz(1), sz(2), sz(3), nFrames, sz(4) / nFrames ) ;\n% derOutputs{1} = permute(derOutputs{1}, [1 2 4 3 5]);\n% \n% \n% derInputs{1} = mex_maxpool3d(derOutputs{1}, idx, sz_in ,...\n% 'pool',obj.poolSize, 'stride', obj.stride, 'pad', obj.pad);\n% \n% derInputs{1} = permute(derInputs{1}, [1 2 4 3 5]);\n% sz_out = size(derInputs{1});\n% if numel(sz_out) < 4, sz_out(4) = 1; end % fixes the case of time being pooled \n% nFrames = sz_out(4); % reset nframes\n% obj.net.meta.curNumFrames(obj.layerIndex) = nFrames; % reset nframes\n% \n% if numel(sz_out) < 5 , sz_out(5) = 1; end % fixes the case of single batch \n% derInputs{1} = reshape(derInputs{1}, sz_out(1), sz_out(2), sz_out(3), nFrames*sz_out(5) ) ; \n% derInputs{1} = derOutputs{1};\n derParams = {};\n \n end\n\n function kernelSize = getKernelSize(obj)\n kernelSize = obj.poolSize ;\n end\n\n function outputSizes = getOutputSizes(obj, inputSizes)\n outputSizes = getOutputSizes@dagnn.Filter(obj, inputSizes) ;\n outputSizes{1}(3) = inputSizes{1}(3) ;\n end\n\n function obj = Pooling(varargin)\n obj.load(varargin) ;\n end\n end\nend\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u8bc6\u522b\u7b97\u6cd5/DAIN-master/matconvnet/matlab/+dagnn/AvePooling3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.39714000314793646}}
{"text": "function d = gcdfactor(A)\nd = A(1);\nfor n = 2:numel(A)\n if d == 1\n return\n else\n d = gcd(d,A(n));\n end\nend", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/extras/gcdfactor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6654105587468141, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.3968729131110647}}
{"text": "%CONCATM Fixed-cell mapping concatenating cell array of datasets or mappings\n%\n% W = V*CONCATM\n% B = A*CONCATM\n%\n% INPUT\n% V Cell array of mappings\n% A Cell array of datasets\n%\n% OUTPUT\n% W Concatenation of mappings: W = [V{:}]\n% A Concatenation of datasets: B = [A{:}]\n%\n% DESCRIPTION\n% This routine is an exception of the general treatment of cell arrays and\n% mappings in PRTools. As a rule the elements of a cell array are processed\n% one by one by a mapping. This routine takes the entire cell array and\n% concatenates its elements.\n%\n% SEE ALSO (PRTools Guide)\n% DATASETS, MAPPINGS\n\n% Copyright: R.P.W. Duin, r.p.w.duin@37steps.com\n\nfunction out = concatm(argin)\n\nif nargin == 0\n out = prmapping(mfilename,'fixed_cell');\nelse\n if ~iscell(argin)\n error('Cell array expected')\n else\n out = [];\n for j=1:size(argin,1)\n out = [out;[argin{j,:}]];\n end\n end\nend", "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/concatm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.3968729131110646}}
{"text": "function A = myspconvert(A, nrows, ncols, tol)\n\n% function A = myspconvert(A, nrows, ncols, tol)\n% Purpose: convert a triplet sparse matrix into a Matlab sparse\n% matrix and crop entries smaller than tol \n\nids = find(abs(A(:,3))>tol);\nA = A(ids, :);\n\n% convert to sparse matrix\nA = spconvert(A);\n\n% pad to required size\nif(size(A,1) e_conn( ) =\\n{\\n');\n if ( nel_dof==4 ) % Test for linear tetrahedra\n for i=1:n_elements\n fprintf(fid,' %6i %6i %6i %6i\\n',e_conn(i,:));\n end\n elseif ( nel_dof==10 ) % Test for quadratic tetrahedra\n for i=1:n_elements\n fprintf(fid,' %6i %6i %6i %6i %6i %6i %6i %6i %6i %6i\\n',...\n e_conn(i,[1 2 3 4 5 6 7 10 8 9]));\n end\n else\n error('threed_to_vu: element type not currently implemented\\n')\n return\n end\n fprintf(fid,'};\\n\\n');\n\n % Write out variables\n for n_var=1:n_variables\n if ( isempty(var(n_var).name) )\n var(n_var).name = strcat('Var',int2str(n_var));\n end\n\n temp = strcat('FIELD@',var(n_var).name,'( ) = {\\n');\n temp = strrep(temp,'D@','D ');\n fprintf(fid,temp);\n fprintf(fid,' %10.5e %10.5e %10.5e %10.5e %10.5e %10.5e \\n',...\n u(:,n_var) );\n fprintf(fid,'\\n};\\n');\n end\n fprintf(fid,'\\n\\n');\n\n % Write out zones and connectivity\n if ( nel_dof==4 )\n fprintf(fid,'MESH MyMesh( ) =\\n{\\n');\n fprintf(fid,' ZONE Zone1( LagrTetra04, x_coord, e_conn );\\n' );\n fprintf(fid,'};\\n\\n');\n elseif ( nel_dof==10 )\n fprintf(fid,'MESH MyMesh( ) =\\n{\\n');\n fprintf(fid,' ZONE Zone1( LagrTetra10, x_coord, e_conn );\\n' );\n fprintf(fid,'};\\n\\n');\n end\n\n fprintf(fid,'SOLUTION MySolution( ) =\\n{\\n');\n if ( nel_dof==4 )\n for n_var=1:n_variables\n temp = strcat(' VARIABLE@' , var(n_var).name,...\n '( LagrTetra04,@', var(n_var).name,...\n ', e_conn, Zone1 );\\n');\n temp = strrep(temp,'@',' ');\n fprintf(fid,temp);\n end\n else\n for n_var=1:n_variables\n temp = strcat(' VARIABLE@' , var(n_var).name,...\n '( LagrTetra10,@', var(n_var).name,...\n ', e_conn, Zone1 );\\n');\n temp = strrep(temp,'@',' ');\n fprintf(fid,temp);\n end\n end\n fprintf(fid,'};\\n');\n\n fclose(fid);\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/threed_to_vu/threed_to_vu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105454764747, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.3968729051961944}}
{"text": "function [type,beats,beatsuct] = beat_class(ecg,qrs,T_LENGTH)\n% this function is used to contruct a template ecg based on the location of\n% the R-peaks. A series of peaks that match with each other are stacked to\n% build a template. This template can then be used for ecg morphological\n% analysis or further processing. Note that the qrs location inputed must\n% be as precise as possible. This approach for building the template ECG\n% seems to be the best of the alternatives that were tested and leaves the\n% freedom of having more than one mode (i.e. multiple ECG template can be\n% built if there are different cycle morphology such as PVC) but it is not\n% particularly fast.\n% The procedure for building the template is:\n% 1. create average wrapped template\n% 2. identify different modes present\n%\n% inputs\n% ecg: the ecg channel(s)\n% qrs: qrs location [number of samples]\n% T_LENGTH template length\n% \n% --\n% ECG classification from single-lead segments using Deep Convolutional Neural \n% Networks and Feature-Based Approaches - December 2017\n% \n% Released under the GNU General Public License\n%\n% Copyright (C) 2017 Fernando Andreotti, Oliver Carr\n% University of Oxford, Insitute of Biomedical Engineering, CIBIM Lab - Oxford 2017\n% fernando.andreotti@eng.ox.ac.uk\n%\n% \n% For more information visit: https://github.com/fernandoandreotti/cinc-challenge2017\n% \n% Referencing this work\n%\n% Andreotti, F., Carr, O., Pimentel, M.A.F., Mahdi, A., & De Vos, M. (2017). \n% Comparing Feature Based Classifiers and Convolutional Neural Networks to Detect \n% Arrhythmia from Short Segments of ECG. In Computing in Cardiology. Rennes (France).\n%\n% Last updated : December 2017\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% == manage inputs\nif nargin<2; error('ecg_template_build: wrong number of input arguments \\n'); end;\n\nif size(ecg,1)>size(ecg,2), ecg = ecg';end\n\n% == constants\n% qrs(1) = []; qrs(end) = []; % remove extremity peaks\nextremities = (qrs <= 2*T_LENGTH | qrs >= length(ecg)-2*T_LENGTH); % test if there are peaks on the border that may lead to error\nqrs = round(qrs(~extremities)); % remove extremity peaks\n\n%% Phase wrap to get all within 2*pi\nNB_BINS = 250; % number of bins for wrapping\n[M,RES] = stackbeats(ecg,qrs,T_LENGTH,NB_BINS);\n \n\n% beatsuct = median(M')';\n% dem = round((length(beatsuct)-2*T_LENGTH-1)/2); \n% beats{1} = beatsuct(dem+1:end-dem);\n% type = ones(length(qrs),1);\n\n%% Clustering\nNclus1 = 5;\nNclus2 = 2;\nM = bsxfun(@times,M,hamming(size(M,1))); % do it twice, it's the\nM = bsxfun(@times,M,hamming(size(M,1))); % magic sauce\nM = bsxfun(@times,M,hamming(size(M,1))); % magic sauce\nM = M';\n% [~, clusters, ~] = fkmeans(M',Nclus);\nrng(1);\n[~,clusters,~] = kmeans(M,Nclus1); % may need to provide centroid..\n[~,clusters,~] = kmeans(clusters,Nclus2); % may need to provide centroid..\nclusters = clusters';\n\n% !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n% TODO: allow more than two clusters!!!!!!!!!!!!!!!!!!!!\n% !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\ncorel = corrcoef(clusters(50:200,1),clusters(50:200,2));\n\n\n%% In case beats are correlated to each other\nif corel(1,2) > 0.7 \n type = ones(size(qrs));\n beats{1} = resample(mean([clusters(:,1), clusters(:,2)],2),RES,NB_BINS); \n dem = (length(beats{1})-2*T_LENGTH-1)/2; \n beatsuct = beats;\n beats = cellfun(@(x) x(dem+1:end-dem),beats,'UniformOutput',0);\n return;\nend\n\n%% In case one cluster has low amplitude\n\nidx = var(clusters)<0.1*var(ecg); % remove clusters with variance less than 10% of signal\nif any(idx)\n type = ones(size(qrs));\n beats{1} = resample(clusters(:,~idx),RES,NB_BINS);\n dem = round((length(beats{1})-2*T_LENGTH-1)/2); \n beatsuct = beats;\n beats = cellfun(@(x) x(dem+1:end-dem),beats,'UniformOutput',0);\n return; \nend\n\n\n%% Classifying beats\n\nbeats{1} = resample(clusters(:,1),RES,NB_BINS);\nbeats{2} = resample(clusters(:,2),RES,NB_BINS);\nbeatsuct = beats;\ndem = (length(beats{1})-2*T_LENGTH-1)/2;\nbeats = cellfun(@(x) x(dem+1:end-dem),beats,'UniformOutput',0);\n \nfor i = 1:length(qrs)\n cor = corrcoef(ecg(qrs(i)-T_LENGTH:qrs(i)+T_LENGTH),beats{1});\n corel(1,i) = cor(1,2);\n cor = corrcoef(ecg(qrs(i)-T_LENGTH:qrs(i)+T_LENGTH),beats{2});\n corel(2,i) = cor(1,2);\nend\n[~,type]=max(corel);\n\nif sum(type==2)>sum(type==1)\n type(type==2) = 3;\n type(type==1) = 2;\n type(type==3) = 2;\nend\n\nif all(type==2)\n type = ones(size(type));\nend\ntype = type';\n \nend\n\n\n", "meta": {"author": "fernandoandreotti", "repo": "cinc-challenge2017", "sha": "78cfc8e6194857cee0cd731f41ba5b2dd589aed2", "save_path": "github-repos/MATLAB/fernandoandreotti-cinc-challenge2017", "path": "github-repos/MATLAB/fernandoandreotti-cinc-challenge2017/cinc-challenge2017-78cfc8e6194857cee0cd731f41ba5b2dd589aed2/featurebased-approach/subfunctions/beat_class.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489892, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3968648665483158}}
{"text": "function glm = glmCreate(tr,nh,whiten)\n%Create a GLM model for managing the GLM parameters\n%\n% glm = glmCreate(tr,nh,whiten)\n%\n%\n\n% It would be better to go and get the TR from the SESSION data.\nif notDefined('tr'), error('You must specify tr for the GLM'); end\nif notDefined('nh'), nh = 22; end\nif notDefined('whiten'), whiten = 0; end\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% initialize GLM model %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nglm.betas = [];\nglm.residual = [];\nglm.stdevs = [];\nglm.sems = [];\nglm.nh = nh; % Number of time samples\nglm.tr = tr; %\nglm.C = []; % Covariance matrix\nglm.voxDepNoise = [];\nglm.voxIndepNoise = [];\nglm.designMatrix = [];\nglm.dof = []; % Degrees of freedom\nglm.whiten = whiten; % Do not whiten the covariance\n\n% glmSet() ...\nif nh>1, glm.type = 'selective averaging';\nelse glm.type = 'applied HRF';\nend\n\nreturn;\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/EventRelated/GLM/glmCreate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.39686486654831576}}
{"text": "function [out] = random(msg,BSID,DIUC,Frame);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% %\n%% Name: random.m %\n%% %\n%% Description: This function is realisez uniquely by the way %\n%% defined in the standard. It is one more stage in the encoding. %\n%% %\n%% %\n%% Parameters: %\n%% msg --> Sequence of bits to encode with the algorithm BSID, %\n%% DIUC, Frame--> Identifiers of the connection that is carried %\n%% out.(Base Station, Downlink and the number of frames) %\n%% %\n%% %\n%% Result: It gives back the chain of bits encoded accordin to %\n%% the need (following DIUC, BSID and Frame). The encoding and %\n%% decoding are an identical process. %\n%% %\n%% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nseed = zeros (1,15);\nseed=[de2bi(BSID,4,'left-msb') 1 1 de2bi(DIUC,4,'left-msb') 1 de2bi(Frame,4,'left-msb')];\n\nout=zeros(1,length(msg));\n\nfor i=1:length(msg)\n next = xor(seed(14),seed(15));\n out(i) = xor( msg(i),next);\n seed = [next seed(1,1:14)];\nend\n\nreturn;\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/21494-a-802-16d-system-comments-on-english/random.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3968648601865095}}
{"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": "% Gtomo_nufft_test.m\n% Test the Gtomo_nufft object\n\n% create Gtomo_nufft class object\nif ~isvar('An'), printm 'setup'\n\tig = image_geom('nx', 64, 'ny', 60, 'fov', 480);\n\tig.mask = ig.circ > 0;\n\tif 1\n\t\tsg = sino_geom('par', 'nb', 70, 'na', 80, 'dr', 7, ...\n\t\t\t'orbit_start', -15, 'strip_width', 'd');\n\t\tfan_arg = {}; % parallel beam\n\telse\n\t\tsg = sino_geom('ge1', 'orbit_start', -15, 'down', 8, ...\n\t\t\t'strip_width', 'd');\n\t\tfan_arg = { % fan beam\n\t\t\t'offset_s', sg.offset_s, ...\n\t\t\t'dis_src_det', sg.dsd, ...\n\t\t\t'dis_iso_det', sg.dod, ...\n\t\t};\n\tend\n\n\t% test non-rect image basis function and beam shape (S. Matej)\n\tif 0\n\t\tbasis.type = 'KB';\n\t\tbasis.diam = 4;\n\t\tbasis.shape = 10.4;\n\t\tbasis.m = 2;\n\t\tbasis.dim = 2;\n\t\tbasis.kernel=[];\n\n\t\t% KB: FWHM~1.0 : J=6, alpha=40, m=2\n\t\tbeam.type = 'KB';\n\t\tbeam.diam = 6;\n\t\tbeam.shape = 40.;\n\t\tbeam.m = 2;\n\tend\n\n\tcpu etic\n\n%{\n\targ_geom = { % for old version\n\t\tfan_arg{:}, ...\n\t\t'orbit', sg.orbit, ...\n\t\t'orbit_start', sg.orbit_start, ...\n\t\t'dx', ig.dx, ...\n\t\t'ds', sg.d, ...\n\t\t'yscale', -ig.dy/ig.dx, ...\n\t\t'strip_width', sg.strip_width, ...\n\t};\n%}\n\n\targ = {\n\t\t'interp', {'table', 2^11, 'minmax:kb'}, ...\n...%\t\t'basis', basis, ...\n...%\t\t'beam', beam, ...\n\t\t'is.complex', 0, ...\n...%\t\t'kaiser', ...\t% use KB interpolator\n...%\t\t'uniform', ...\n...%\t\t'bilin', ...\n...%\t\t'is.test', 1, ...\n\t\t'class', 'fatrix2', ...\n\t};\n\n%\tAo = Gtomo_nufft(ig.mask, [sg.nb sg.na], arg_geom{:}, arg{:});\n\tAn = Gtomo_nufft_new(sg, ig, arg{:});\n%\tjf_equal(struct(Ao), struct(An)), return\n\n\tcpu etoc 'An pre time:'\nend\n\n%\n% make test image\n%\nif 0\n%\tx = ig.zeros;\n%\tx(12, 8) = 1;\n%\tx((nx/4+1):(3*nx/4),(ny/4+1):(3*ny/4)) = 1;\n\tx = ig.unitv(ig.nx/4,ig.ny/3);\t% point source\nelseif 1\n\tx = ellipse_im(ig, [0 0 [1 1]*ig.ny*ig.dx*0.9/2 0 1], 'oversample', 2);\n\tx(end/4:end/2,end/4:end/2) = 1.25;\nelse\n\tix = [-(nx-1)/2:(nx-1)/2]/nx;\n\tiy = [-(ny-1)/2:(ny-1)/2]/ny;\n\t[ix iy] = ndgrid(ix, iy);\n\tx = exp(-(ix.^2 + iy.^2) / 10^2);\nend\n\n% check real / imaginary\nif 1\n\ty = An * x(ig.mask);\n\ty = sg.shape(y);\n\tim plc 3 3\n\tim(1, x, 'x')\n\tim(2, real(y), 'real(An*x)'), cbar\n\tim(3, imag(y), 'imag(An*x)'), cbar\nprompt\nend\n\n% DSFT version for comparison\nif ~isvar('Ad'), printm 'Ad'\n%\tAo = Gtomo_nufft(ig.mask, [sg.nb sg.na], arg_geom{:}, arg{:}, ...\n%\t\t'is.dsft2', 1, 'is.dsft1', 1);\n\tAd = Gtomo_nufft_new(sg, ig, arg{:}, 'is.dsft2', 1, 'is.dsft1', 1);\n%\tjf_equal(struct(Ao), struct(Ad)), return\nend\n\n% create a \"strip integral\" system object\nif ~isvar('As'), printm 'As'\n%\tAo = aspire_pair(sg, ig, 'strip_width', An.arg.strip_width, ...\n%\t\t'support', 'all');\n%\t\t'support', ig.mask);\n%\tAo = Gtomo2_dscmex(Ao, 'nthread', 2); % multiprocessor!\n\tAs = Gtomo2_dscmex(sg, ig, 'nthread', 2); % multiprocessor!\n%\tjf_equal(struct(Ao), struct(As)), return\nend\n\n% compare back projectors\nif 0\n\ty = sg.ones;\n\ty = sg.unitv(sg.nb/2+7, 9);\n%\ty = yd / 100;\n\txn = An' * y;\n\txd = Ad' * y;\n\txs = As' * y;\n\tim(4, xn, 'An''*y'), cbar\n\tim(5, xd, 'Ad''*y'), cbar\n\tim(6, xs, 'As''*y'), cbar\n\tim(8, xn-xd, 'An''*y - Ad''*y'), cbar\n\tim(9, xn-xs, 'An''*y - As''*y'), cbar\n%\tprintf('back nrms = %g%%', nrms(x2(:), x1(:)) * 100)\nprompt\nend\n\n% compare projectors\nif 1\n\tyn = An * x;\n\tyd = Ad * x;\n\tys = As * x;\n\tim(4, yd, 'Ad*x'), cbar\n\tim(5, yn-yd, 'An*x-Ad*x'), cbar\n\tim(7, ys, 'As*x'), cbar\n\tim(8, yn-ys, 'An*x-As*x'), cbar\n%\tprintf('forward nrms = %g%%', nrms(y2(:), y1(:)) * 100)\nprompt\nend\n\nif 1, printm 'single ray'\n\ty = sg.unitv(sg.nb/2+9,1);\n\tim pl 2 3\n\tim(1, As'*y, 'back ray strip'), cbar h\n\tim(2, An'*y, 'back ray nufft'), cbar h\n\tim(3, Ad'*y, 'back ray dsft'), cbar h\n\tim(4, An'*y - Ad'*y, 'nufft - dsft'), cbar h\n\tim(5, An'*y - As'*y, 'nufft - strip'), cbar h\n\tim(6, Ad'*y - As'*y, 'dsft - strip'), cbar h\nreturn\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/systems/tests/Gtomo_nufft_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3968648601865095}}
{"text": "% File Name: resampling.m\n% Author: Heung-Il Suk\n% Cite: H.-I. Suk and S.-W. Lee, \"A Novel Bayesian Framework for Discriminative \n% Feature Extraction in Brain-Computer Interfaces,\" IEEE Trans. on PAMI,\n% 2012. (Accepted)\n\nfunction newBSSFO = resamplingBSSFO( oldBSSFO )\n\naccWeight = cumsum( oldBSSFO.weight );\n\nfor i=1:oldBSSFO.numBands\n oldBSSFO.selected( i ) = 0;\nend\n\nnewBSSFO = oldBSSFO;\nfor i=1:oldBSSFO.numBands\n idx = find( accWeight > rand );\n newBSSFO.sample(:, i) = oldBSSFO.sample( :, idx(1) );\n if oldBSSFO.selected( idx(1) ) == 0\n oldBSSFO.selected( idx(1) ) = 1;\n newBSSFO.selected( i ) = 1; % keep current state, do not add random noise\n end\nend\n\nnewBSSFO.weight = ones(newBSSFO.numBands, 1)./ newBSSFO.numBands;", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/GigaScience/function_MI/bssfo/original/resamplingBSSFO.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.3967822138993633}}
{"text": "function plotActivityTrace( inferred, filtered, raw, plotControl)\n\n% This code plots the activity trace for all the ROIs\n% Author: Weijian Yang\n\n% input parameters:\n% inferred, filtered, raw (from the output of \"signalExtraction.m\")\n% plotControl.frameRate: frame rate in fps\n% plotControl.normalization: normalize the amplitude of the temporal trace for plotting purpose\n% plotControl.sep: vertical (amplitude) offset between adjacent temporal traces \n% plotControl.displayLabel: whether to display ROI ID for the temporal traces \n% plotControl.plotInferred: whether the inferred signal is plotted\n% plotControl.plotFiltered: whether the filtered signal is plotted\n% plotControl.plotRaw: whether the raw signal is plotted\n% plotControl.rollingView: whether the display is set such that only 20 temporal traces are displayed at a time, followed by any key to move onto the next 20 traces, and etc.\n\nif isfield(plotControl,'frameRate') frameRate=plotControl.frameRate;\nelse frameRate=1; end\n\nif isfield(plotControl,'normalization') normalization=plotControl.normalization;\nelse normalization=1; end\n\nif isfield(plotControl,'sep') sep=plotControl.sep;\nelse sep=1.2; end\n\nif isfield(plotControl,'displayLabel') displayLabel=plotControl.displayLabel;\nelse displayLabel=1; end\n\nif isfield(plotControl,'plotInferred') plotInferred=plotControl.plotInferred;\nelse plotInferred=1; end\n\nif isfield(plotControl,'plotFiltered') plotFiltered=plotControl.plotFiltered;\nelse plotFiltered=1; end\n\nif isfield(plotControl,'plotRaw') plotRaw=plotControl.plotRaw;\nelse plotRaw=0; end\n\nif isfield(plotControl,'rollingView') rollingView=plotControl.rollingView;\nelse rollingView=0; end\n\nt=1/frameRate*(1:size(inferred,2));\nK=size(inferred,1);\n\nfigure;\nhold on;\n\nif normalization==1\n for idx=1:K\n if plotRaw plot(t,raw(idx,:)/max(raw(idx,:))-idx*sep,'color',[0.8 0.8 0.8],'linewidth',2); end\n if plotFiltered plot(t,filtered(idx,:)/max(filtered(idx,:))-idx*sep,'color',[1 0.7 0.7],'linewidth',1.5); end\n if plotInferred plot(t,inferred(idx,:)/max(inferred(idx,:))-idx*sep,'color',[0 0 1],'linewidth',1); end\n end\n ylabel('Normalized \\DeltaF/F');\nelse\n for idx=1:K\n if plotRaw plot(t,raw(idx,:)-idx*sep,'color',[0.8 0.8 0.8],'linewidth',2); end\n if plotFiltered plot(t,filtered(idx,:)-idx*sep,'color',[1 0.7 0.7],'linewidth',1.5); end\n if plotInferred plot(t,inferred(idx,:)-idx*sep,'color',[0 0 1],'linewidth',1); end\n end \n ylabel('\\DeltaF/F');\nend\nxlabel('Time (s)');\n\nif displayLabel\n for idx=1:K\n text(max(t)*1.02,-idx*sep, num2str(idx));\n end\nend\n\nh=gca;\nif ~rollingView \n axis(h,[0 max(t) -sep*(K+1) sep]);\nelse\n idx=1;\n displayNum=20;\n while idx+displayNum 100, Ibar = floor(linspace(1, D.ntrials, 100));\nelse Ibar = 1:D.ntrials; end\n\nfor i = 1:D.ntrials\n \n Dnew(:, :, i) = spm_squeeze(mean(D(:, freqind, :, i), 2), 2);\n \n if any(Ibar == i), spm_progress_bar('Set', i); end\nend\n\nspm_progress_bar('Clear');\n\n%-Save the new M/EEG dataset\n%--------------------------------------------------------------------------\nDnew = Dnew.history(mfilename, S);\nsave(Dnew);\n\nD = Dnew;\n\n%-Cleanup\n%--------------------------------------------------------------------------\nfprintf('%-40s: %30s\\n','Completed',spm('time')); %-#\nspm('FigName','Average over frequency: done'); spm('Pointer','Arrow');\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_eeg_avgfreq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370111, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.3967757573269965}}
{"text": "classdef ExistProbCalculatorX < BaseX \n% ExistProbCalculatorX class\n%\n% Summary of ExistProbCalculatorX:\n% This class can be used to compute (recursively) the existence probability\n% of tracks.\n%\n% ExistProbCalculatorX Properties:\n% TrackList\n% AssocWeightsMatrix\n% ProbOfDetection\n% ProbOfDeath\n% ProbOfGating\n%\n% ExistProbCalculatorX Methods:\n% + ExistProbCalculatorX - Constructor method\n% + calculate - Calculate the existence probabilities\n%\n% (+) denotes public properties/methods\n%\n% March 2018 Lyudmil Vladimirov, University of Liverpool.\n \n properties\n TrackList\n AssocWeightsMatrix\n ProbOfDetection\n ProbOfDeath\n ProbOfGating\n end\n \n methods\n function this = ExistProbCalculatorX(varargin)\n % EXISTPROBCALCULATORX Constructor method\n %\n % Parameters\n % ----------\n % ProbOfDetection: scalar\n % A scalar value in the range [0,1] which specifies the probability\n % of detection for all targets\n % ProbOfDeath: scalar\n % A scalar value in the range [0,1] which specifies the probability\n % of death for all targets\n % ProbOfGating: scalar\n % A scalar value in the range [0,1] which specifies the probability\n % of gating for all targets\n % \n % Usage\n % -----\n % * ExistProbCalculatorX() returns a ExistProbCalculatorX object handle.\n % * ExistProbCalculatorX(ProbOfDetection,ProbOfDeath,ProbOfGating) returns \n % a ExistProbCalculatorX( object handle configured with the provided\n % probability of detection ProbOfDetection, probability of death ProbOfDeath \n % and probability of gating ProbOfGating. This is particularly\n % useful when all targets are characterised by the same parameters.\n % * ExistProbCalculatorX(config) can also be used, where config is a\n % structure with fields config.ProbOfDetection, config.ProbOfDeath and\n % config.ProbOfGating.\n % * PhdTrackInitiatorX(___,Name,Value) instantiates an object \n % handle, configured with additional options specified by one or\n % more Name,Value pair arguments.\n \n if(nargin==0)\n return;\n end\n \n % First check to see if a structure was received\n if(nargin==1)\n if(isstruct(varargin{1}))\n config = varargin{1};\n this.ProbOfDetection = config.ProbOfDetection;\n this.ProbOfDeath = config.ProbOfDeath;\n this.ProbOfGating = config.ProbOfGating;\n end\n return;\n elseif(nargin==3)\n this.ProbOfDetection = varargin{1};\n this.ProbOfDeath = varargin{2};\n this.ProbOfGating = varargin{3};\n return;\n end\n \n % Otherwise, fall back to input parser\n parser = inputParser;\n parser.KeepUnmatched = true;\n parser.parse(varargin{:});\n config = parser.Unmatched;\n this.ProbOfDetection = config.ProbOfDetection;\n this.ProbOfDeath = config.ProbOfDeath;\n this.ProbOfGating = config.ProbOfGating;\n end\n \n function argout = calculate(this,varargin)\n % CALCULATE Calculates the probability(ies) of existence\n % \n % Parameters\n % ----------\n % varargin{1}: (1 x NumTracks) cell array or TrackX object\n % Either, a cell array of TrackX objects or a single TrackX\n % object.\n % varargin{2}: (NumTracks x Nm+1) or (1 x Nm+1) matrix\n % In the case that varargin{1} is a cell array, varargin{2}\n % should be a (NumTracks x Nm+1) matrix, else it should be a \n % (1 x Nm+1) row vector, where in both cases, each column contains \n % the association weight between a measurement and a track. The\n % first column corresponds to the dummy measurement.\n %\n % Returns\n % -------\n % argout: (1 x NumTracks) cell array or TrackX object\n % Either, a cell array of TrackX objects or a single TrackX\n % object, with their/its ProbOfExist field updated\n %\n % Usage\n % -----\n % * TrackList = calculate(this,TrackList,AssocWeightsMatrix) \n % computes the new probability of existence for each TrackX\n % object in TrackList and returns the updated TrackList\n % * Track = calculate(this,Track,AssocWeightsMatrix) \n % computes the new probability of existence for the TrackX\n % object Track and returns the updated Track\n if(isempty(varargin{1}))\n argout = varargin{1};\n return\n end\n if(iscell(varargin{1}))\n % Compute Existence Probabilities\n this.TrackList = varargin{1};\n this.AssocWeightsMatrix = varargin{2};\n numTracks = numel(this.TrackList);\n for trackInd = 1:numTracks\n this.TrackList{trackInd}.ProbOfExist = (1 - this.ProbOfDeath)*this.TrackList{trackInd}.ProbOfExist;\n denom = sum(this.AssocWeightsMatrix(trackInd,:))*this.TrackList{trackInd}.ProbOfExist + this.AssocWeightsMatrix(trackInd,1)*(1-this.TrackList{trackInd}.ProbOfExist)/((1-this.ProbOfDetection*this.ProbOfGating));\n this.TrackList{trackInd}.ProbOfExist = (sum(this.AssocWeightsMatrix(trackInd,:))*this.TrackList{trackInd}.ProbOfExist)/denom;\n end\n argout = this.TrackList;\n elseif(isa(varargin{1},'TrackX'))\n Track = varargin{1};\n AssocWeights = varargin{2};\n Track.ProbOfExist = (1 - this.ProbOfDeath)*Track.ProbOfExist;\n denom = sum(AssocWeights)*Track.ProbOfExist + AssocWeights(1)*(1-Track.ProbOfExist)/((1-this.ProbOfDetection*this.ProbOfGating));\n Track.ProbOfExist = (sum(AssocWeights)*Track.ProbOfExist)/denom;\n argout = Track;\n end\n end \n end\nend", "meta": {"author": "sglvladi", "repo": "TrackingX", "sha": "f737445c070f0d7d470f52f8a2b5540d5bb682da", "save_path": "github-repos/MATLAB/sglvladi-TrackingX", "path": "github-repos/MATLAB/sglvladi-TrackingX/TrackingX-f737445c070f0d7d470f52f8a2b5540d5bb682da/Generic/ExistProbCalculatorX/ExistProbCalculatorX.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850154599562, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.39677575036890717}}
{"text": "function x = triu( x, k )\n\n% Disciplined convex/geometric programming information for TRIU:\n% TRIU imposes no convexity restrictions on its arguments.\n\n%\n% Check inputs\n%\n\nif nargin < 2, k = 0; end\ns = x.size_;\nif length( s ) > 2,\n error( 'The first argument must be 2-D.' );\nelseif ~isnumeric( k ) || length( k ) ~= 1,\n error( 'The second argument must be an integer scalar.' );\nend\n\n%\n% Zero out the elements outside of the desired triangle\n%\n\nb = x.basis_;\nb( :, ~triu(ones(s),k) ) = 0;\nx = cvx( s, b );\n\n% Copyright 2005-2016 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": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/builtins/@cvx/triu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7057850154599563, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.3967757503689071}}
{"text": "function [imageCha, ssim_map, metrics] = algo_SB_proxA_2D_real( obj,input )\n% 2D variant of SB\n% based on Goldstein and Oshers paper on Split Bregman\n%\n% input:\n% obj CS reconstruction object (holding all parameters)\n% input struct containing recon parameters and image\n%\n% output:\n% imageCha reconstructed channel individual image\n% ssim_map structural similarity map\n% metrics evaluation metrics \n%\n% (c) Marc Fischer, Thomas Kuestner, May 2015\n% -------------------------------------------------------------------------\n\n%%\ntimer_proxA = tic;\n\n%% variables:\n% internal flags\nflag_wavetree = true;\nflag_fast = true;\nflag_extendImage = true;\n\n% internal variables:\nL = 1;\nt_old = 1;\nNLTV_struct.kernelratio = 3;\nNLTV_struct.windowratio = 6;\nNLTV_struct.nThreads = 1; % mind this option if used with -singleCompThread on BWCluster\nitrNLTV = obj.maxitr - 20;\n% chambolle tv:\nparsin.MAXITER=100; parsin.tv='iso'; % 'iso' or 'l1'\n\n% from obj:\n% maxitr = obj.maxitr;\nmaxitr = obj.iNINNER;\n% maxitrOUTER = obj.maxitrOUTER;\nmaxitrOUTER = obj.iNOUTER;\nmaxitrINNER = ceil( maxitr / maxitrOUTER );\n% n1 = obj.measPara.dim(1);\n% n2 = obj.measPara.dim(2);\nn1 = input.n1;\nn2 = input.n2;\n% nSlices = obj.measPara.dim(3);\nnCha = obj.measPara.dim(5);\nlambdaWave = obj.lambda;\nlambdaTV = obj.lambdaTV;\nlambdaGroup = obj.lambdaGroup;\nNLTV_struct.filterstrength = obj.lambdaNLTV_h; % 0.03 % converted from NLTV h = 0.01 %old: used: 3e-10\nlambdaNLTV = obj.lambdaNLTV;\nlambdaNLTV_h = obj.lambdaNLTV_h;\nmue = obj.mue;\nregularizerWeights = obj.regularizerWeights;\nflagTV = obj.flagTV;\nflagTV_iso = obj.flagTV_iso;\nflagWave = obj.flagWave;\nflagGroup = obj.flagGroup;\nflagNLTV = obj.flagNLTV;\nflagSBNLTV = obj.flagSBNLTV;\nwaveletStages = obj.trafo.waveletStages;\nwaveletFilterName_l1 = obj.trafo.waveletFilterName_l1;\nwaveletFilterName_l12 = obj.trafo.waveletFilterName_l12;\n\n% from input:\nb=input.b;\nmask = input.mask;\nG_prox = input.G_prox;\nGt_prox = input.Gt_prox;\ngroupnorm_index = input.groupnorm_index;\nwaveS_l1 = input.waveS_l1;\nwaveS_l12 = input.waveS_l12;\nwaveS_l12proxA = input.waveS_l12proxA;\nproxA_extend_y = waveS_l12proxA(waveletStages+2,1) - waveS_l12(waveletStages+2,1);\nproxA_extend_x = waveS_l12proxA(waveletStages+2,2) - waveS_l12(waveletStages+2,2);\nx_proxA = cell(1,nCha);\n\n% im_ref = input.im_ref;\n% im_ref_full = zeros(n1,n2);\n% for j = 1:nCha\n% im_ref_full = im_ref_full + abs(im_ref{1,j}).^2;\n% end;\n% im_ref_full = sqrt(im_ref_full);\nclear input\n\n% initialize cells/vectors\nfor j=1:nCha\n FTb{1,j} = real(iFFT2D(b{1,j}));\n % y{1,j} = real(FTb{1,j});\n % y{1,j+nCha} = imag(FTb{1,j});\nend;\n% starting point:\nx = FTb; % (x0 = FTb)\nrhs = FTb; % different start (x0 = F^-1 K^-1 F FTb); %used atm\nb_outer = b;\n% rhs: right hand side\n\nx_wave = cell(1,nCha);\nx_g_proxA = x_wave;\nx_g_helper = cell(2,nCha);\nx_wave_helper = rhs;\nv_wave = rhs;\nd_wave = rhs;\nx_tv = rhs;\nv_tv = rhs;\nd_tv = rhs;\nx_group = rhs;\nv_group = rhs;\nd_group = rhs;\nx_nltv = rhs;\nv_nltv = rhs;\nd_nltv = rhs;\nK_inv = rhs;\nfor j = 1:nCha\n x_wave{1,j} = 0;\n v_wave{1,j} = 0;\n d_wave{1,j} = 0;\n x_tv{1,j} = zeros(n1,n2);\n v_tv{1,j} = 0;\n d_tv{1,j} = 0;\n x_group{1,j} = 0;\n v_group{1,j} = 0;\n d_group{1,j} = 0;\n x_nltv{1,j} = 0;\n v_nltv{1,j} = 0;\n d_nltv{1,j} = 0;\nend;\n\n%% MAD dependent lambdas:\nflag_MAD = true;\nif flag_MAD\n x_wavedec = cell(1,nCha);\n threshold = zeros(1:nCha);\n for j=1:nCha % 2*nCha\n x_wavedec{1,j} = wavedec2(x{1,j},waveletStages,waveletFilterName_l1); % atm only based on l1-daubechie\n x_wave_fine_scale = size(x_wavedec{1,j},2) - (3*waveS_l1(waveletStages+1,1)*waveS_l1(waveletStages+1,2));\n threshold(j) = mad(x_wavedec{1,j}(x_wave_fine_scale:end),1);\n end;\n clear x_wavedec\nelse\n threshold(1:nCha) = 1;\nend;\n\nthreshold_wave(j) = lambdaWave * threshold(j) * 2/L;\nthreshold_TV(j) = lambdaTV * threshold(j) * 2/L;\nthreshold_group(j) = lambdaGroup * threshold(j) * 2/L;\nthreshold_NLTV(j) = lambdaNLTV; % * threshold(j) * 2/L;\nthreshold_NLTV_h(j) = lambdaNLTV_h; %*threshold(j); % adjust carefully or NLTV won't find a solution. lambdaNLTV_h should be < 0.01\n\n%% initialize metrics:\nitr = 0;\nmetrics.xtime(itr+1)= 0;\n% [metrics, ssim_map{1,1}] = get_metrics_itr( im_ref, im_ref_full, x, itr, maxitr, nCha, n1, n2, metrics, obj.K_1, obj.K_2, obj.W_size, obj.W_sigma );\nssim_map = [];\n\n%% recon\n% inverse for x - step:\nfor j = 1:nCha\n K_inv{1,j} = 1./(mue*mask + (flagWave*regularizerWeights(1) + flagTV*regularizerWeights(2) + flagGroup*regularizerWeights(3))*ones(n1,n2)); % flagNLTV changes K_inv -> in separate\nend;\n\ndispProgress('Proximal Average', 0, maxitrOUTER*maxitrINNER);\nitr = 0;\nfor itrOUTER = 1:maxitrOUTER % total iter counter\n for itrINNER = 1:maxitrINNER\n \n %% x - step\n if itr > 1 % for i = 1 already set (x{1,j} = FTb{1,j})\n for j = 1:nCha\n % rhs part:\n if flagWave\n x_wave{1,j} = waverec2((v_wave{1,j} - d_wave{1,j}),waveS_l1,waveletFilterName_l1); end;\n if flagTV\n x_tv{1,j} = v_tv{1,j} - d_tv{1,j}; end;\n if flagGroup\n x_g_proxA{1,j} = waverec2((v_group{1,j} - d_group{1,j}),waveS_l12proxA,waveletFilterName_l12);\n x_group{1,j} = x_g_proxA{1,j}(1:end-proxA_extend_y,1:end-proxA_extend_x);\n end;\n if flagNLTV\n if itr == itrNLTV\n K_inv{1,j} = 1./(mue*mask + (flagWave*regularizerWeights(1) + flagTV*regularizerWeights(2) + flagGroup*regularizerWeights(3) + flagNLTV*regularizerWeights(4))*ones(n1,n2));\n x_nltv{1,j} = x{1,j};\n elseif itr >= itrNLTV\n x_nltv{1,j} = v_nltv{1,j} - d_nltv{1,j};\n end;\n end;\n rhs{1,j} = mue*FTb{1,j} + ( flagWave*regularizerWeights(1).*(x_wave{1,j}) + flagTV*regularizerWeights(2).*(x_tv{1,j}) + flagGroup*regularizerWeights(3).*(x_group{1,j}) + flagNLTV*regularizerWeights(4).*(x_nltv{1,j}));\n x{1,j} = real(iFFT2D(K_inv{1,j}.*FFT2D(rhs{1,j})));\n end;\n end;\n \n %% auxiliary variables:\n %% l1-Wavelet\n if flagWave\n for j = 1:nCha\n x_wave_helper{1,j} = wavedec2(x{1,j},waveletStages,waveletFilterName_l1);\n v_wave{1,j} = softthresh_real((x_wave_helper{1,j} + d_wave{1,j}),threshold_wave(j));\n d_wave{1,j} = d_wave{1,j} + x_wave_helper{1,j} - v_wave{1,j};\n end;\n end;\n \n %% TV:\n if flagTV\n if ~flagTV_iso\n for j = 1:nCha\n v_tv{1,j} = MTV_2D((x{1,j} + d_tv{1,j}), threshold_TV(j), n1, n2);\n end;\n else\n for j = 1:nCha\n if (itr < 2)\n [v_tv{1,j}, P]=denoise_TV_One((x{1,j} + d_tv{1,j}), threshold_TV(j),-inf,inf,[],parsin);\n else\n [v_tv{1,j}, P]=denoise_TV_One((x{1,j} + d_tv{1,j}), threshold_TV(j),-inf,inf,P,parsin);\n end;\n end;\n end;\n d_tv{1,j} = d_tv{1,j} + x{1,j} - v_tv{1,j};\n end;\n \n %% NLTV\n if flagNLTV\n if itr >= itrNLTV\n if flagSBNLTV\n for j = 1:nCha\n v_nltv{1,j} = SB_NLTVfunc_slim_rescale( (x{1,j} + d_nltv{1,j}),n1,n2, threshold_NLTV(j), threshold_NLTV_h(j) );\n end;\n else\n for j = 1:nCha\n % if mod(itr,5) == 0 || itr == 1\n v_nltv{1,j} = NLMF((x{1,j} + d_nltv{1,j}),NLTV_struct);\n v_nltv{1,j} = (L.*(x{1,j} + d_nltv{1,j}) + 2*threshold_NLTV(j)*v_nltv{1,j})./(L+2*threshold_NLTV(j));\n % end;\n end;\n end;\n d_nltv{1,j} = d_nltv{1,j} + x{1,j} - v_nltv{1,j};\n else\n v_nltv{1,j} = 0;\n d_nltv{1,j} = 0;\n end;\n \n end;\n \n %% l12-Wavelet\n if flagGroup\n for j = 1:nCha\n if flag_extendImage\n x_proxA{1,j} = extend_image(x{1,j}, waveS_l12proxA, waveletStages, proxA_extend_y, proxA_extend_x);\n x_g_helper{1,j} = wavedec2(x_proxA{1,j},waveletStages,waveletFilterName_l12) + d_group{1,j};\n else\n x_g_helper{1,j} = wavedec2(x{1,j},waveletStages,waveletFilterName_l12) + d_group{1,j};\n end;\n \n if flag_wavetree\n x_g_helper{2,j} = (G_prox*x_g_helper{1,j}')';\n else\n x_g_helper{2,j} = zeros(1,size(x_g_helper{1,j},2));\n end;\n end;\n \n % softthresh_proxA_cha returns cell! hence (1,:) assignement\n v_group(1,:) = softthresh_proxA_cha(x_g_helper,threshold_group(j),nCha,waveS_l12proxA,groupnorm_index);\n \n for j = 1:nCha\n d_group{1,j} = d_group{1,j} + x_g_helper{1,j} - v_group{1,j};\n end;\n end;\n \n %% metrics of current itr:\n itr = itr + 1;\n% disp(itr);\n dispProgress('Proximal Average', itr/(maxitrOUTER*maxitrINNER));\n \n metrics.xtime(itr+1)= toc(timer_proxA);\n% [metrics, ssim_map{1,2}] = get_metrics_itr( im_ref, im_ref_full, x, itr, maxitr, nCha, n1, n2, metrics, obj.K_1, obj.K_2, obj.W_size, obj.W_sigma );\n \n if itr >= maxitr break; end;\n end;\n if itr >= maxitr break; end;\n for j=1:nCha\n b_outer{1,j} = b_outer{1,j} + b{1,j} - FFT2D_mask(x{1,j},mask);\n FTb{1,j} = real(iFFT2D(b_outer{1,j}));\n end;\nend;\ndispProgress('Proximal Average', 'Close');\n\nimageCha = x;\nfor j = 1:nCha\n imageCha{1,j} = turn_image( imageCha{1,j} );\nend;\n% for j = 1:nCha+1\n% ssim_map{1,1}{1,j} = turn_image( ssim_map{1,1}{1,j} );\n% ssim_map{1,2}{1,j} = turn_image( ssim_map{1,2}{1,j} );\n% end;\n\nend", "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/@Proximal/algo_SB_proxA_2D_real.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3966814823144408}}
{"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, 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 (nickabattista@gmail.com) know.\n%\n%--------------------------------------------------------------------------------------------------------------------%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: updates the spring attributes!\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction springs_info = update_Springs(dt,current_time,xLag,yLag,springs_info)\n\n%springs_info: col 1: starting spring pt (by lag. discretization)\n% col 2: ending spring pt. (by lag. discretization)\n% col 3: spring stiffness\n% col 4: spring resting lengths\n\n%RL = springs_info(:,4); % resting-length vector\n\nfreq = 0.875;\n%theta=freq*current_time*2*pi;\n%phase = sin(theta);\n\n%size(springs_info)\n\n%springs_info(1:3,:)\n%pause();\n\n% CHANGE RESTING LENGTH BTWN SIDES OF JELLYFISH BELL\n%springs_info(319:end,4) = phase;\n\nsprings_info(319:end,4) = abs( sin(0.875*current_time*2*pi) );\n\n\n% if ( mod(current_time,0.875) < 0.875/2 ) \n% springs_info(319:end,4) = abs( sin(0.875*current_time*2*pi) );\n% else\n% springs_info(319:end,4) = 0;%abs( sin(0.875*current_time*2*pi) );\n% end\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/Failed_Attempts/Jellyfish_IBAMR_Convert/update_Springs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3966814823144408}}
{"text": "%% Machine Learning Online Class\n% Exercise 8 | Anomaly Detection and Collaborative Filtering\n%\n% Instructions\n% ------------\n%\n% This file contains code that helps you get started on the\n% exercise. You will need to complete the following functions:\n%\n% estimateGaussian.m\n% selectThreshold.m\n% cofiCostFunc.m\n%\n% For this exercise, you will not need to change any code in this file,\n% or any other files other than those mentioned above.\n%\n\n%% =============== Part 1: Loading movie ratings dataset ================\n% You will start by loading the movie ratings dataset to understand the\n% structure of the data.\n% \nfprintf('Loading movie ratings dataset.\\n\\n');\n\n% Load data\nload ('ex8_movies.mat');\n\n% Y is a 1682x943 matrix, containing ratings (1-5) of 1682 movies on \n% 943 users\n%\n% R is a 1682x943 matrix, where R(i,j) = 1 if and only if user j gave a\n% rating to movie i\n\n% From the matrix, we can compute statistics like average rating.\nfprintf('Average rating for movie 1 (Toy Story): %f / 5\\n\\n', ...\n mean(Y(1, R(1, :))));\n\n% We can \"visualize\" the ratings matrix by plotting it with imagesc\nimagesc(Y);\nylabel('Movies');\nxlabel('Users');\n\n%fprintf('\\nProgram paused. Press enter to continue.\\n');\n%pause;\n\n%% ============ Part 2: Collaborative Filtering Cost Function ===========\n% You will now implement the cost function for collaborative filtering.\n% To help you debug your cost function, we have included set of weights\n% that we trained on that. Specifically, you should complete the code in \n% cofiCostFunc.m to return J.\n\n% Load pre-trained weights (X, Theta, num_users, num_movies, num_features)\nload ('ex8_movieParams.mat');\n\n% Reduce the data set size so that this runs faster\nnum_users = 4; num_movies = 5; num_features = 3;\nX = X(1:num_movies, 1:num_features);\nTheta = Theta(1:num_users, 1:num_features);\nY = Y(1:num_movies, 1:num_users);\nR = R(1:num_movies, 1:num_users);\n\n% Evaluate cost function\nJ = cofiCostFunc([X(:) ; Theta(:)], Y, R, num_users, num_movies, ...\n num_features, 0);\n \nfprintf(['Cost at loaded parameters: %f '...\n '\\n(this value should be about 22.22)\\n'], J);\n\nfprintf('\\nProgram paused. Press enter to continue.\\n');\npause;\n\n\n%% ============== Part 3: Collaborative Filtering Gradient ==============\n% Once your cost function matches up with ours, you should now implement \n% the collaborative filtering gradient function. Specifically, you should \n% complete the code in cofiCostFunc.m to return the grad argument.\n% \nfprintf('\\nChecking Gradients (without regularization) ... \\n');\n\n% Check gradients by running checkNNGradients\ncheckCostFunction;\n\nfprintf('\\nProgram paused. Press enter to continue.\\n');\npause;\n\n\n%% ========= Part 4: Collaborative Filtering Cost Regularization ========\n% Now, you should implement regularization for the cost function for \n% collaborative filtering. You can implement it by adding the cost of\n% regularization to the original cost computation.\n% \n\n% Evaluate cost function\nJ = cofiCostFunc([X(:) ; Theta(:)], Y, R, num_users, num_movies, ...\n num_features, 1.5);\n \nfprintf(['Cost at loaded parameters (lambda = 1.5): %f '...\n '\\n(this value should be about 31.34)\\n'], J);\n\nfprintf('\\nProgram paused. Press enter to continue.\\n');\npause;\n\n\n%% ======= Part 5: Collaborative Filtering Gradient Regularization ======\n% Once your cost matches up with ours, you should proceed to implement \n% regularization for the gradient. \n%\n\n% \nfprintf('\\nChecking Gradients (with regularization) ... \\n');\n\n% Check gradients by running checkNNGradients\ncheckCostFunction(1.5);\n\nfprintf('\\nProgram paused. Press enter to continue.\\n');\npause;\n\n\n%% ============== Part 6: Entering ratings for a new user ===============\n% Before we will train the collaborative filtering model, we will first\n% add ratings that correspond to a new user that we just observed. This\n% part of the code will also allow you to put in your own ratings for the\n% movies in our dataset!\n%\nmovieList = loadMovieList();\n\n% Initialize my ratings\nmy_ratings = zeros(1682, 1);\n\n% Check the file movie_idx.txt for id of each movie in our dataset\n% For example, Toy Story (1995) has ID 1, so to rate it \"4\", you can set\nmy_ratings(1) = 4;\n\n% Or suppose did not enjoy Silence of the Lambs (1991), you can set\nmy_ratings(98) = 2;\n\n% We have selected a few movies we liked / did not like and the ratings we\n% gave are as follows:\nmy_ratings(7) = 3;\nmy_ratings(12)= 5;\nmy_ratings(54) = 4;\nmy_ratings(64)= 5;\nmy_ratings(66)= 3;\nmy_ratings(69) = 5;\nmy_ratings(183) = 4;\nmy_ratings(226) = 5;\nmy_ratings(355)= 5;\n\nfprintf('\\n\\nNew user ratings:\\n');\nfor i = 1:length(my_ratings)\n if my_ratings(i) > 0 \n fprintf('Rated %d for %s\\n', my_ratings(i), ...\n movieList{i});\n end\nend\n\nfprintf('\\nProgram paused. Press enter to continue.\\n');\npause;\n\n\n%% ================== Part 7: Learning Movie Ratings ====================\n% Now, you will train the collaborative filtering model on a movie rating \n% dataset of 1682 movies and 943 users\n%\n\nfprintf('\\nTraining collaborative filtering...\\n');\n\n% Load data\nload('ex8_movies.mat');\n\n% Y is a 1682x943 matrix, containing ratings (1-5) of 1682 movies by \n% 943 users\n%\n% R is a 1682x943 matrix, where R(i,j) = 1 if and only if user j gave a\n% rating to movie i\n\n% Add our own ratings to the data matrix\nY = [my_ratings Y];\nR = [(my_ratings ~= 0) R];\n\n% Normalize Ratings\n[Ynorm, Ymean] = normalizeRatings(Y, R);\n\n% Useful Values\nnum_users = size(Y, 2);\nnum_movies = size(Y, 1);\nnum_features = 10;\n\n% Set Initial Parameters (Theta, X)\nX = randn(num_movies, num_features);\nTheta = randn(num_users, num_features);\n\ninitial_parameters = [X(:); Theta(:)];\n\n% Set options for fmincg\noptions = optimset('GradObj', 'on', 'MaxIter', 100);\n\n% Set Regularization\nlambda = 10;\ntheta = fmincg (@(t)(cofiCostFunc(t, Y, R, num_users, num_movies, ...\n num_features, lambda)), ...\n initial_parameters, options);\n\n% Unfold the returned theta back into U and W\nX = reshape(theta(1:num_movies*num_features), num_movies, num_features);\nTheta = reshape(theta(num_movies*num_features+1:end), ...\n num_users, num_features);\n\nfprintf('Recommender system learning completed.\\n');\n\nfprintf('\\nProgram paused. Press enter to continue.\\n');\npause;\n\n%% ================== Part 8: Recommendation for you ====================\n% After training the model, you can now make recommendations by computing\n% the predictions matrix.\n%\n\np = X * Theta';\nmy_predictions = p(:,1) + Ymean;\n\nmovieList = loadMovieList();\n\n[r, ix] = sort(my_predictions, 'descend');\nfprintf('\\nTop recommendations for you:\\n');\nfor i=1:10\n j = ix(i);\n fprintf('Predicting rating %.1f for movie %s\\n', my_predictions(j), ...\n movieList{j});\nend\n\nfprintf('\\n\\nOriginal ratings provided:\\n');\nfor i = 1:length(my_ratings)\n if my_ratings(i) > 0 \n fprintf('Rated %d for %s\\n', my_ratings(i), ...\n movieList{i});\n end\nend\n", "meta": {"author": "worldveil", "repo": "coursera-ml", "sha": "94e205b01ec3a47c0d777943194d12fa130f4685", "save_path": "github-repos/MATLAB/worldveil-coursera-ml", "path": "github-repos/MATLAB/worldveil-coursera-ml/coursera-ml-94e205b01ec3a47c0d777943194d12fa130f4685/recommender/code/ex8_cofi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.7154239957834734, "lm_q1q2_score": 0.39668147558590927}}
{"text": "function [labels adjlist pE] = trimapGenerateMultipleSegmentations2( image, imsegs, edgeClassifier, ecal, t, size_array )\n adjmat = imsegs.adjmat;\n segimage = imsegs.segimage;\n \n spFeat = getSuperpixelData_ver2(image, imsegs);\n [edgeFeat adjlist] = getEdgeData_ver2( imsegs, spFeat );\n% spFeat = mcmcGetSuperpixelData( image, imsegs );\n% [edgeFeat adjlist] = mcmcGetEdgeData( imsegs, spFeat );\n pE=test_boosted_dt_mc(edgeClassifier,edgeFeat);\n pE = 1 ./ (1+exp(ecal(1)*pE+ecal(2)));\n \n nSuperpixel = max(segimage(:));\n % labels = mexMergeAdjacentRegions2( adjlist, pE, nSuperpixel, t );\n labels = mexMergeAdjRegs_Felzenszwalb( adjlist, pE, nSuperpixel, t, size_array );\n \n% image_lab = rgb2lab( image );\n% bins = [8 16 16];\n% Q = computeQuantMatrix( image_lab, bins );\n% region_hist = computeRegionHist(Q, bins, segimage);\n% \n% num_region = max(segimage(:));\n% region_dist = zeros(num_region, num_region);\n% \n% ind = find(adjmat);\n% for ix = 1 : length(ind)\n% [x y] = ind2sub([num_region, num_region], ind(ix));\n% region_dist(x, y) = histDist(region_hist(x,:), region_hist(y,:));\n% end\n% \n% t = 0.2:0.05:0.8;\n% labels = mexMergeAdjacentRegions(region_dist, t);\n \n for jx = 1 : size(labels, 2)\n L = labels(:, jx);\n temp_label = unique(L);\n for ix = 1 : length(temp_label)\n idx = find( L == temp_label(ix) );\n labels(idx, jx) = ix;\n end\n end\n ", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u68c0\u6d4b\u7b97\u6cd5/drfi_matlab-master/multi-segmentation/trimapGenerateMultipleSegmentations2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3966814755859092}}
{"text": "classdef dme_line3p < mp.dm_element\n%MP.DME_LINE3P MATPOWER data model class for 3-phase line data\n\n% MATPOWER\n% Copyright (c) 2021-2022, 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 properties\n fbus %% bus index vector for \"from\" port (port 1) (all lines)\n tbus %% bus index vector for \"to\" port (port 2) (all lines)\n freq %% system frequency, in Hz\n lc %% index into lc_tab for lines that are on\n len %% length for lines that are on\n lc_tab %% line construction table\n ys %% cell array of 3x3 series admittance matrices for lc rows\n yc %% cell array of 3x3 shunt admittance matrices for lc rows\n end %% properties\n\n methods\n function name = name(obj)\n name = 'line3p';\n end\n\n function label = label(obj)\n label = '3-ph Line';\n end\n\n function label = labels(obj)\n label = '3-ph Lines';\n end\n\n function name = cxn_type(obj)\n name = 'bus3p';\n end\n\n function name = cxn_idx_prop(obj)\n name = {'fbus', 'tbus'};\n end\n\n function names = main_table_var_names(obj)\n names = horzcat( main_table_var_names@mp.dm_element(obj), ...\n {'bus_fr', 'bus_to', 'lc', 'len', ...\n 'pl1_fr', 'ql1_fr', 'pl2_fr', 'ql2_fr', 'pl3_fr', 'ql3_fr', ...\n 'pl1_to', 'ql1_to', 'pl2_to', 'ql2_to', 'pl3_to', 'ql3_to' ...\n });\n end\n\n% function vars = export_vars(obj)\n% vars = {'pl1_fr', 'ql1_fr', ...\n% 'pl2_fr', 'ql2_fr', ...\n% 'pl3_fr', 'ql3_fr', ...\n% 'pl1_to', 'ql1_to', ...\n% 'pl2_to', 'ql2_to', ...\n% 'pl3_to', 'ql3_to' };\n% end\n\n function obj = initialize(obj, dm)\n initialize@mp.dm_element(obj, dm); %% call parent\n\n %% get bus mapping info\n b2i = dm.elements.bus3p.ID2i; %% bus num to idx mapping\n\n %% set bus index vectors for port connectivity\n obj.fbus = b2i(obj.tab.bus_fr);\n obj.tbus = b2i(obj.tab.bus_to);\n end\n\n function obj = update_status(obj, dm)\n %% get bus status info\n bs = dm.elements.bus3p.tab.status; %% bus status\n\n %% update status of branches connected to isolated/offline buses\n obj.tab.status = obj.tab.status & bs(obj.fbus) & ...\n bs(obj.tbus);\n\n %% call parent to fill in on/off\n update_status@mp.dm_element(obj, dm);\n end\n\n function obj = build_params(obj, dm)\n nlc = size(obj.lc, 1);\n obj.ys = zeros(nlc, 6);\n obj.yc = zeros(nlc, 6);\n obj.lc = obj.tab.lc(obj.on);\n obj.len = obj.tab.len(obj.on);\n\n %% build Ys and Yc for relevant lines\n idx = unique(obj.lc);\n rr = obj.lc_tab.r(idx, :);\n xx = obj.lc_tab.x(idx, :);\n cc = obj.lc_tab.c(idx, :);\n% rr = obj.lc_tab{idx, 2:7};\n% xx = obj.lc_tab{idx, 8:13};\n% cc = obj.lc_tab{idx, 14:19};\n for k = 1:length(idx)\n R = obj.vec2symmat(rr(k, :));\n X = obj.vec2symmat(xx(k, :));\n C = obj.vec2symmat(cc(k, :));\n Ys = inv(R + 1j * X);\n Yc = 1j * 2*pi * obj.freq * 1e-9 * C;\n obj.ys(k, :) = obj.symmat2vec(Ys);\n obj.yc(k, :) = obj.symmat2vec(Yc);\n end\n end\n\n function M = vec2symmat(obj, v)\n % makes a symmetric matrix from a vector of 6 values\n M = [v(1) v(2) v(3);\n v(2) v(4) v(5);\n v(3) v(5) v(6) ];\n end\n\n function v = symmat2vec(obj, M)\n % extracts a vector of 6 values from a matrix assumed to be symmetric\n v = [M(1, :) M(2,2:3) M(3,3)];\n end\n\n function obj = pretty_print(obj, dm, section, out_e, mpopt, fd, pp_args)\n switch section\n case 'det'\n %% compute currents/powers for pp_args\n s_fr = [ obj.tab.pl1_fr + 1j * obj.tab.ql1_fr ...\n obj.tab.pl2_fr + 1j * obj.tab.ql2_fr ...\n obj.tab.pl3_fr + 1j * obj.tab.ql3_fr ];\n s_to = [ obj.tab.pl1_to + 1j * obj.tab.ql1_to ...\n obj.tab.pl2_to + 1j * obj.tab.ql2_to ...\n obj.tab.pl3_to + 1j * obj.tab.ql3_to ];\n t = dm.elements.bus3p.tab; %% bus3p table\n vm = [ t.vm1 t.vm2 t.vm3 ] .* (t.base_kv/sqrt(3) * [1 1 1]);\n va = [ t.va1 t.va2 t.va3 ];\n v_ = vm .* exp(1j * va * pi/180);\n i_fr = conj( s_fr ./ v_(obj.fbus, :));\n i_to = conj( s_to ./ v_(obj.tbus, :));\n c_fr = struct('cm', abs(i_fr), 'ca', angle(i_fr) * 180/pi);\n c_to = struct('cm', abs(i_to), 'ca', angle(i_to) * 180/pi);\n\n pp_args.line3p = {'c', 'f', abs(i_fr), angle(i_fr) * 180/pi};\n pretty_print@mp.dm_element(obj, dm, section, out_e, mpopt, fd, pp_args);\n\n pp_args.line3p = {'c', 't', abs(i_to), angle(i_to) * 180/pi};\n pretty_print@mp.dm_element(obj, dm, section, out_e, mpopt, fd, pp_args);\n\n pp_args.line3p = {'s', 'f', real(s_fr), imag(s_fr)};\n pretty_print@mp.dm_element(obj, dm, section, out_e, mpopt, fd, pp_args);\n\n pp_args.line3p = {'s', 't', real(s_to), imag(s_to)};\n pretty_print@mp.dm_element(obj, dm, section, out_e, mpopt, fd, pp_args);\n otherwise\n pretty_print@mp.dm_element(obj, dm, section, out_e, mpopt, fd, pp_args);\n end\n end\n\n function TorF = pp_have_section_sum(obj, mpopt, pp_args)\n TorF = true;\n end\n\n function obj = pp_data_sum(obj, dm, rows, out_e, mpopt, fd, pp_args)\n %% call parent\n pp_data_sum@mp.dm_element(obj, dm, rows, out_e, mpopt, fd, pp_args);\n\n %% print generation summary\n t = obj.tab;\n ploss = [ t.pl1_fr t.pl2_fr t.pl3_fr ] + ...\n [ t.pl1_to t.pl2_to t.pl3_to ];\n qloss = [ t.ql1_fr t.ql2_fr t.ql3_fr ] + ...\n [ t.ql1_to t.ql2_to t.ql3_to ];\n fprintf(fd, ' %-29s %12.1f kW %12.1f kVAr\\n', 'Total 3-ph line loss', ...\n sum(sum(ploss(obj.on, :))), sum(sum(qloss(obj.on, :))) );\n end\n\n function TorF = pp_have_section_det(obj, mpopt, pp_args)\n TorF = true;\n end\n\n function h = pp_get_headers_det(obj, dm, out_e, mpopt, pp_args)\n cs = pp_args.line3p{1};\n ft = pp_args.line3p{2};\n if cs == 'c' && ft == 'f'\n h1 = pp_get_headers_det@mp.dm_element(obj, dm, out_e, mpopt, pp_args);\n else\n h1 = {};\n end\n if cs == 'c'\n if ft == 'f'\n h2 = {'--> Current Injections at \"From\" Bus' };\n else %% ft == 't'\n h2 = {'', ...\n '<-- Current Injections at \"To\" Bus' };\n end\n else %% cs == 's'\n if ft == 'f'\n h2 = {'', ...\n '--> Power Injections at \"From\" Bus' };\n else %% ft == 't'\n h2 = {'', ...\n '<-- Power Injections at \"To\" Bus' };\n end\n end\n switch cs\n case 'c'\n h = [ h1 h2 ...\n { ' 3-ph 3-ph Bus 3-ph Bus Phase A Current Phase B Current Phase C Current', ...\n 'Line ID From ID To ID Status (A) (deg) (A) (deg) (A) (deg)', ...\n '-------- -------- -------- ------ ------ ------ ------ ------ ------ ------' } ];\n %% 1234567 123456789 123456789 -----1 123456.89 12345.7 12345.78 12345.7 12345.78 12345.7\n case 's'\n h = [ h1 h2 ...\n { ' 3-ph 3-ph Bus 3-ph Bus Phase A Power Phase B Power Phase C Power', ...\n 'Line ID From ID To ID Status (kW) (kVAr) (kW) (kVAr) (kW) (kVAr)', ...\n '-------- -------- -------- ------ ------ ------ ------ ------ ------ ------' } ];\n %% 1234567 123456789 123456789 -----1 1234567.9 12345.7 123456.8 12345.7 123456.8 12345.7\n end\n end\n\n function str = pp_data_row_det(obj, dm, k, out_e, mpopt, fd, pp_args)\n switch pp_args.line3p{1} %% cs\n case 'c'\n cm = pp_args.line3p{3}(k, :);\n ca = pp_args.line3p{4}(k, :);\n str = sprintf('%7d %9d %9d %6d %9.2f %7.1f %8.2f %7.1f %8.2f %7.1f', ...\n obj.tab.uid(k), obj.tab.bus_fr(k), obj.tab.bus_to(k), ...\n obj.tab.status(k), ...\n cm(:, 1), ca(:, 1), ...\n cm(:, 2), ca(:, 2), ...\n cm(:, 3), ca(:, 3) );\n case 's'\n p = pp_args.line3p{3}(k, :);\n q = pp_args.line3p{4}(k, :);\n str = sprintf('%7d %9d %9d %6d %9.1f %7.1f %8.1f %7.1f %8.1f %7.1f', ...\n obj.tab.uid(k), obj.tab.bus_fr(k), obj.tab.bus_to(k), ...\n obj.tab.status(k), ...\n p(:, 1), q(:, 1), ...\n p(:, 2), q(:, 2), ...\n p(:, 3), q(:, 3) );\n end\n end\n end %% methods\nend %% classdef\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/lib/+mp/dme_line3p.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3966460941306852}}
{"text": "clear;\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% indicate the super-resolution factor\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ndown_factor = 3; % 2, 3 or 4\nimage_path = 'data/deepeaf/BSDS500/';\ndata_chs = 1; % 1 or 3\ntraining_mat_path = 'data/Shepard_CNN/Shepard_super_res/x3/train_1ch/';\nval_mat_path = 'data/Shepard_CNN/Shepard_super_res/x3/val_1ch/';\n\npatch_dim = 48;\nnum_patches = 20000;\nlisting = dir(strcat(image_path, '*.jpg'));\nmat_num = 51;\nfor m = 1 : mat_num\n fprintf('Extracting patch batch: %d / %d\\n', m, mat_num);\n % extract random patches\n images = zeros(patch_dim, patch_dim, data_chs, num_patches);\n labels = zeros(size(images));\n for i = 1 : num_patches\n if (mod(i,100) == 0)\n fprintf('Extracting patch: %d / %d\\n', i, num_patches);\n end\n \n r_idx = random('unid', size(listing, 1));\n I = im2double(imread(strcat(image_path, listing(r_idx).name)));\n orig_img_size = size(I);\n r = random('unid', orig_img_size(1) - patch_dim + 1);\n c = random('unid', orig_img_size(2) - patch_dim + 1);\n \n patch = I(r:r+patch_dim-1, c:c+patch_dim-1, :);\n \n if(data_chs == 1)\n patch = rgb2ycbcr(patch);\n patch = patch(:,:,1);\n end \n \n patch_down = imresize(patch, [patch_dim/down_factor, patch_dim/down_factor], 'bicubic');\n patch_up = imresize(patch_down, [patch_dim, patch_dim], 'nearest');\n images(:,:,:,i) = patch_up;\n labels(:,:,:,i) = patch;\n %imshow([patch_up patch]); pause;\n end\n % save it\n images = single(images);\n labels = single(labels);\n \n if(m >= mat_num)\n % save validation data\n filename = strcat(val_mat_path, 'val_1');\n images_t = images;\n labels_t = labels;\n save(filename, '-v7.3', 'images_t', 'labels_t');\n else\n % save training data\n filename = strcat(training_mat_path, 'patches_', num2str(m));\n save(filename, '-v7.3', 'images', 'labels');\n end\nend\n\n\n\n", "meta": {"author": "jimmy-ren", "repo": "vcnn_double-bladed", "sha": "a4de90e845875f6e30632f2e879d3afb81c0ebc1", "save_path": "github-repos/MATLAB/jimmy-ren-vcnn_double-bladed", "path": "github-repos/MATLAB/jimmy-ren-vcnn_double-bladed/vcnn_double-bladed-a4de90e845875f6e30632f2e879d3afb81c0ebc1/data/Shepard_CNN/Shepard_super_res/gen_training_data.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.3966460941306851}}
{"text": "function [ t_start, y_start ] = p29_start ( neqn )\n\n%*****************************************************************************80\n%\n%% P29_START returns the starting point for problem p29.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 February 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NEQN, the number of equations.\n%\n% Output, real T_START, Y_START(NEQN,1), the initial data.\n%\n y_start = zeros ( neqn, 1 );\n\n t_start = 0.0;\n y_start = 1.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_ode/p29_start.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.7634837527911056, "lm_q1q2_score": 0.39664608853898004}}
{"text": "function value = i4vec_index ( n, a, aval )\n\n%*****************************************************************************80\n%\n%% I4VEC_INDEX returns the first location of a given value in an I4VEC\n%\n% Discussion:\n%\n% An I4VEC is a vector of integer values.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 05 November 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of entries in the vector.\n%\n% Input, integer A(N), the vector to be searched.\n%\n% Input, integer AVAL, the value to be indexed.\n%\n% Output, integer VALUE, the first location in A which has the\n% value AVAL, or -1 if no such index exists.\n%\n for i = 1 : n\n if ( a(i) == aval )\n value = i;\n return\n end\n end\n\n value = -1;\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_mat/i4vec_index.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.396644999960752}}
{"text": "function range = p18_range ( )\n\n%*****************************************************************************80\n%\n%% P18_RANGE returns an interval bounding the root for problem 18.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 October 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Output, real RANGE(2), the minimum and maximum values of\n% an interval containing the root.\n%\n range(1) = 0.988;\n range(2) = 1.012;\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_zero/p18_range.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.3966449913714559}}
{"text": "function r = YZRectangle(x,y1,y2,z1,z2)\n\n%YZRECTANGLE Rectangle in the YZ plane.\n\n% Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n\n\ns1 = ySegment(x,y1,y2,z1);\ns2 = zSegment(x,y2,z1,z2);\ns3 = ySegment(x,y2,y1,z2);\ns4 = zSegment(x,y1,z2,z1);\n\nr = [s1 s2 s3 s4];\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/Simulation/YZRectangle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.39661606488357015}}
{"text": "classdef lowrank\n% Generates matrices of low rank\n\nmethods(Static)\n\nfunction A = from_randn(m, n, r)\n % Returns a low rank matrix constructed by randn(m, r) * randn(r, m)\n X = randn(m, r);\n Y = randn(r, n);\n A = X * Y;\nend % function\n\nend % methods\n\nend % classdef\n", "meta": {"author": "indigits", "repo": "sparse-plex", "sha": "43cae2978f62938d001baaa03308a2a717ee6c9b", "save_path": "github-repos/MATLAB/indigits-sparse-plex", "path": "github-repos/MATLAB/indigits-sparse-plex/sparse-plex-43cae2978f62938d001baaa03308a2a717ee6c9b/library/+spx/+data/+synthetic/lowrank.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.3966160517552894}}
{"text": "function dcline = psse_convert_hvdc(dc, bus)\n%PSSE_CONVERT_HVDC Convert HVDC data from PSS/E RAW to MATPOWER\n% DCLINE = PSSE_CONVERT_HVDC(DC, BUS)\n%\n% Convert all two terminal HVDC line data read from a PSS/E\n% RAW data file into MATPOWER format. Returns a dcline matrix for\n% inclusion in a MATPOWER case struct.\n%\n% Inputs:\n% DC : matrix of raw two terminal HVDC line data returned by\n% PSSE_READ in data.twodc.num\n% BUS : MATPOWER bus matrix\n%\n% Output:\n% DCLINE : a MATPOWER dcline matrix suitable for inclusion in\n% a MATPOWER case struct.\n%\n% See also PSSE_CONVERT.\n\n% MATPOWER\n% Copyright (c) 2014-2016, Power Systems Engineering Research Center (PSERC)\n% by Yujia Zhu, PSERC ASU\n% and Ray Zimmerman, PSERC Cornell\n% Based on mpdcin.m and mpqhvdccal.m, written by:\n% Yujia Zhu, Jan 2014, yzhu54@asu.edu.\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 bus, gen, branch 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;\nc = idx_dcline;\n\nnb = size(bus, 1);\nndc = size(dc, 1);\ne2i = sparse(bus(:, BUS_I), ones(nb, 1), 1:nb, max(bus(:, BUS_I)), 1);\nif ~ndc\n dcline = [];\n return;\nend\n\n%% extract data\nMDC = dc(:,2); % Control mode\nSETVL = dc(:,4); % depend on control mode: current or power demand\nVSCHD = dc(:,5); % scheduled compounded dc voltage\nANMXR = dc(:,15); % nominal maximum rectifier firing angle\nANMNR = dc(:,16); % nominal minimum rectifier firing angle\nGAMMX = dc(:,32); % nominal maximum inverter firing angle\nGAMMN = dc(:,33); % nominal minimum inverter firing angle\nSETVL = abs(SETVL);\n% Convert the voltage on rectifier side and inverter side\n% The value is calculated as basekV/VSCHD\n% basekV is the bus base voltage, VSCHD is the scheduled compounded\n% voltage\ndcline = zeros(ndc, c.LOSS1); % initiate the hvdc data format\nindr = dc(:,13); % rectifier end bus number\nindi = dc(:,30); % inverter end bus number\ndcind = [indr indi]; \n% bus nominal voltage\nVr = bus(e2i(indr), VM);\nVi = bus(e2i(indi), VM);\n%% Calculate the real power input at the from end\nPMW = zeros(ndc, 1);\nfor i = 1:ndc\n if MDC(i) == 1\n PMW(i) = SETVL(i); % SETVL is the desired real power demand\n elseif MDC(i) == 2;\n PMW(i) = SETVL(i)*VSCHD(i)/1000; % SETVL is the current in amps (need devide 1000 to convert to MW)\n else PMW(i) = 0;\n end\nend\n%% calculate reactive power limits\n[Qrmin,Qrmax] = psse_convert_hvdc_Qlims(ANMXR,ANMNR,PMW); %% rectifier end\n[Qimin,Qimax] = psse_convert_hvdc_Qlims(GAMMX,GAMMN,PMW); %% inverter end\n%% calculate the loss coefficient (Only consider the l1)\n% l1 = P'.*RDC;\n\n%% conclude all info\nstatus = ones(ndc, 1);\nstatus(MDC==0) = 0; %% set status of blocked HVDC lines to zero\n% dcline(:,[1 2 3 4 5 8 9 10 11 12 13 14 15]) = [indr,indi,status,PMW, PMW, Vr, Vi,0.85*PMW, 1.15*PMW, Qrmin, Qrmax, Qimin, Qimax];\ndcline(:, [c.F_BUS c.T_BUS c.BR_STATUS c.PF c.PT c.VF c.VT ...\n c.PMIN c.PMAX c.QMINF c.QMAXF c.QMINT c.QMAXT]) = ...\n [indr indi status PMW PMW Vr Vi 0.85*PMW 1.15*PMW Qrmin Qrmax Qimin Qimax];\n\n\nfunction [Qmin, Qmax] = psse_convert_hvdc_Qlims(alphamax,alphamin,P)\n%PSSE_CONVERT_HVDC_QLIMS calculate HVDC line reactive power limits\n%\n% [Qmin, Qmax] = psse_convert_hvdc_Qlims(alphamax,alphamin,P)\n%\n% Inputs:\n% alphamax : maximum firing angle\n% alphamin : minimum steady-state rectifier firing angle\n% P : real power demand\n% Outputs:\n% Qmin : lower limit of reactive power\n% Qmax : upper limit of reactive power \n%\n% Note:\n% This function calculates the reactive power at the rectifier or inverter\n% end. It is assumed the maximum overlap angle is 60 degree (see\n% Kimbark's book). The maximum reactive power is calculated with the\n% power factor:\n% pf = acosd(0.5*(cosd(alphamax(i))+cosd(60))),\n% where, 60 is the maximum delta angle.\n\nlen = length(alphamax);\nphi = zeros(size(alphamax));\nQmin = phi;\nQmax = phi;\nfor i = 1:len\n %% minimum reactive power calculated under assumption of no overlap angle\n %% i.e. power factor equals to tan(alpha)\n Qmin(i) = P(i)*tand(alphamin(i));\n\n %% maximum reactive power calculated when overlap angle reaches max\n %% value (60 deg). I.e.\n %% cos(phi) = 1/2*(cos(alpha)+cos(delta))\n %% Q = P*tan(phi)\n phi(i) = acosd(0.5*(cosd(alphamax(i))+cosd(60)));\n Qmax(i) = P(i)*tand(phi(i));\n if Qmin(i)<0\n Qmin(i) = -Qmin(i);\n end\n if Qmax(i)<0\n Qmax(i) = -Qmax(i);\n end\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/psse_convert_hvdc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458153, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.396593703981257}}
{"text": "%script v0730\nwhile 1\n if or(x(k)==si,y(k)==1)|(v==2)\n break\n end\n xk1=x(k)+1; yk1=y(k)-1;\n if I(xk1,yk1)\n break\n end\n xk2=xk1-1;yk2=yk1;\n tr=(I(xk2,yk2)>0)|I(xk1,y(k));\n if tr\n per=per+1;\n pr=pr+sqrt(2);\n if xk1==si\n per=per+1;\n else\n per=per+I(xk1+1,yk1);\n end\n if yk1==1\n per=per+1;\n else\n per=per+I(xk1,yk1-1);\n end \n k=k+1;v=6;\n x=[x xk1]; y=[y yk1];\n else\n break\n end\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/13924-path-tracing-measuarement-fragmentation/v0730.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 wevent = segment_event_waveforms(w, cobj, pretrigger, posttrigger, arrivalTimeCorrection)\n%SEGMENT_EVENT_WAVEFORMS take a continuous vector of waveforms, and based\n% arrival times in the infrasoundEvent vector, generate a cell vector where\n% each element is a waveform vector extracted around the arrival times\n% given\n% Usage:\n% wevent = segment_event_waveforms(w, infrasoundEvent, pretrigger,\n% posttrigger,arrivalTimeCorrection)\n% pretrigger and posttrigger are in seconds (e.g. 1)\nif ~exist('arrivalTimeCorrection','var')\n arrivalTimeCorrection = 0.0;\nend\ndisp('Segmenting event waveforms...')\nnumEvents = numel(infrasoundEvent);\nfor eventNumber=1:numEvents\n fprintf('- segmenting infrasound event %d of %d\\n',eventNumber,numEvents );\n time1 = infrasoundEvent(eventNumber).FirstArrivalTime-pretrigger/86400-arrivalTimeCorrection/86400;\n% if arrivalTimeCorrection==0.0\n% time2 = infrasoundEvent(eventNumber).LastArrivalTime+posttrigger/86400-arrivalTimeCorrection/86400;\n% else\n time2 = infrasoundEvent(eventNumber).FirstArrivalTime+posttrigger/86400-arrivalTimeCorrection/86400;\n% end\n w2 = detrend(extract(w, 'time', time1, time2));\n wevent{eventNumber} = w2;\n clear w2\nend\n", "meta": {"author": "geoscience-community-codes", "repo": "GISMO", "sha": "a4eafca9d2ac85079253510005ef00aa9998d030", "save_path": "github-repos/MATLAB/geoscience-community-codes-GISMO", "path": "github-repos/MATLAB/geoscience-community-codes-GISMO/GISMO-a4eafca9d2ac85079253510005ef00aa9998d030/applications/rockets/infrasoundgt/segment_event_waveforms.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": "%%*****************************************************************************\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 newRxnScores = groupRxnScores(model, origRxnScores, origRxnIds, groupIds, origRxnsToZero)\n% groupRxnScores\n% This function sums up the reaction scores for all reactions that were merged \n% into one by the linear merge.\n% \n% model The model with linearly merged rxns.\n% origRxnScores The rxnScores from the model before the linear merge.\n% origRxnIds The rxn ids of the model before the linear merge.\n% groupIds The groupIds vector output from linearMerge.\n% There is one integer for each rxn in origRxnIds. 0 means\n% the reaction was merged. A non-zero integer means that the\n% reaction was merged with all other rxns having the same integer.\n% origRxnsToZero A logical vector saying which of the original rxns that should not\n% be part of the problem. The way this is solved is that all \n% such reactions have a rxnScore of 0. If any original rxnScore \n% value should be zero (which is very unlikely) it is changed to 0.01.\n% If the sum of the rxnScores for a merged rxn becomes zero \n% while some of them are nonzero, the new value will also be 0.01, \n% to distinguish the rxn from rxns with only rxns to zero.\n% There are two reasons why we don't want zeros in the reaction \n% scores unless these reactions should be ignored:\n% 1) we want to be able to separate those\n% 2) it is difficult to handle a zero value in the MILP - \n% the on/off of such a reaction can be random, so better \n% to fix it in one direction.\n\n\nnewRxnScores = zeros(length(model.rxns),1);\n[~,ia,ib] = intersect(model.rxns,origRxnIds);\ngrpIdsMerged = nan(length(model.rxns),1);\ngrpIdsMerged(ia) = groupIds(ib);\n%check if any of the original scores are 0, in that case change them to 0.01 (unlikely)\norigRxnScores(origRxnScores == 0) = 0.01;\n%Then set the rxn scores for rxns to zero to 0\norigRxnScores(origRxnsToZero) = 0;\n\n%fill in original scores\nnewRxnScores(ia) = origRxnScores(ib);\n\nfor i = 1:length(model.rxns)\n %for reactions that are not merged with anything, just keep score as it is\n if grpIdsMerged(i) ~= 0\n %find all original rxns in the group\n sel = groupIds == grpIdsMerged(i);\n newRxnScores(i) = sum(origRxnScores(sel));\n if (newRxnScores(i) == 0 && any(origRxnScores(sel) ~= 0))\n %special unfortunate case, where the reactions happen to sum to 0 while some of them are nonzero\n %set to 0.01 in this case (proabably pretty unusual)\n newRxnScores(i) = 0.01;\n end\n end\nend\n\nend\n", "meta": {"author": "SysBioChalmers", "repo": "RAVEN", "sha": "cf4d3e0be954fde96a1a09ae3353dd2ee46552ed", "save_path": "github-repos/MATLAB/SysBioChalmers-RAVEN", "path": "github-repos/MATLAB/SysBioChalmers-RAVEN/RAVEN-cf4d3e0be954fde96a1a09ae3353dd2ee46552ed/INIT/groupRxnScores.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.39659368960688024}}
{"text": " function y = ir_phantom_resize(x, nx, ny)\n%function y = ir_phantom_resize(x, nx, ny)\n%| resize a [mx,my] phantom image to be [nx,ny]\n%| by combination of downsampling and cropping\n\nif nargin == 1 && streq(x, 'test'), ir_phantom_resize_test, return, end\nif nargin < 3, ir_usage, end\n\nmx = size(x,1);\nmy = size(x,2);\nif nx == mx && ny == my\n\ty = x;\n\treturn\nend\n\nif nx > mx || ny > my\n\terror 'requested size too large, implement interpolation!'\nend\n\n% if power of 2 size, then downsample\nif 2^floor(log2(nx)) == nx && nx == ny\n\ty = downsample2(x, mx/nx);\nreturn\nend\n\nnn = 2^max(ceil(log2([nx ny])));\ny = downsample2(x, mx/nn);\n\n% trim if non power of 2\nif nx < nn\n\ty = y([1:nx]+round((nn-nx)/2),:);\nend\nif ny < nn\n\ty = y(:,[1:ny]+round((nn-ny)/2));\nend\n\n\nfunction ir_phantom_resize_test\nx = zeros(64, 60);\nx(20:30,10:15) = 1;\ny = ir_phantom_resize(x, 32, 28);\nim plc 1 2\nim(1, x)\nim(2, y)\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/data/ir_phantom_resize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.39659348903123115}}
{"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 y = apply_3d_func(f,x)\n\n% apply_3d_func - apply a function to 3D arrays\n%\n% y = apply_3d_func(f,x);\n%\n% f should take a 2D NxNxN image and ouput a 2D NxNxN image\n% x is an N^3 x Q input\n% x is an N^3 x Q input\n%\n% This function is used to adapt 3D functions (e.g. filtering) for the \n% barycenter code that assume 1D vectors.\n%\n% Copyright (c) 2014 Gabriel Peyre\n\nN = round( (size(x,1))^(1/3) );\nP = size(x,2);\n\nresh = @(x)reshape(x,[N N N]);\nflat = @(x)x(:);\n\ny = zeros(size(x));\nfor i=1:P\n y(:,i) = flat(f(resh(x(:,i))));\nend\n\nend", "meta": {"author": "gpeyre", "repo": "2015-SIGGRAPH-convolutional-ot", "sha": "484b83c5ee396f3d998f67ed35652249b5e29e81", "save_path": "github-repos/MATLAB/gpeyre-2015-SIGGRAPH-convolutional-ot", "path": "github-repos/MATLAB/gpeyre-2015-SIGGRAPH-convolutional-ot/2015-SIGGRAPH-convolutional-ot-484b83c5ee396f3d998f67ed35652249b5e29e81/code/toolbox/apply_3d_func.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6334102636778403, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.3965934801932504}}
{"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 [ RGBpersp, XYZpersp ] = ht_Points2Persp( RGB, XYZ, P, H, W )\n%RGB, XYZ: 3*(#Number of Points)\n%P = K * [R, t]\n%H, W: size of output perspective\n\n%outputs\nRGBpersp = nan(H, W, 3);\nXYZpersp = nan(H, W, 3);\n\n%XYZ->image coordinate\nUV = P * [XYZ; ones(1, size(XYZ, 2))];\nUV_norm = UV(3, :);\nUV = bsxfun(@rdivide, UV(1:2, :), UV_norm);\n\n% keyboard;\n\nfront_idx = UV_norm > 0;\nUV = UV(:, front_idx);\nRGB = RGB(:, front_idx);\nXYZ = XYZ(:, front_idx);\nUV_norm = UV_norm(front_idx);\n\nvisible_idx = UV(1, :) >= 0 & UV(2, :) >= 0 & UV(1, :) < W & UV(2, :) < H;\nUV = UV(:, visible_idx);\nRGB = RGB(:, visible_idx);\nXYZ = XYZ(:, visible_idx);\nUV_norm = UV_norm(visible_idx);\n\n% UV= 1 + uint16(UV);\n% UV = UV(:, UV_norm>0);\n% UV_norm = UV_norm(UV_norm>0);\n% RGB = RGB(:, UV_norm>0);\n% XYZ = XYZ(:, UV_norm>0);\n% \n% UV = UV(:, UV(1, :) <=W & UV(2, :) <= H);\n% UV_norm = UV_norm(UV(1, :) <=W & UV(2, :) <= H);\n% RGB = RGB(:, UV(1, :) <=W & UV(2, :) <= H);\n% XYZ = XYZ(:, UV(1, :) <=W & UV(2, :) <= H);\n\n% keyboard;\n\n%rendering\nUV = 1 + uint16(floor(UV));\ncheck_norm = ones(H, W) * max(UV_norm);\nfor pp = 1:1:size(UV, 2)\n if UV_norm(pp) <= check_norm(UV(2, pp), UV(1, pp))\n RGBpersp(UV(2, pp), UV(1, pp), 1) = RGB(1, pp);\n RGBpersp(UV(2, pp), UV(1, pp), 2) = RGB(2, pp);\n RGBpersp(UV(2, pp), UV(1, pp), 3) = RGB(3, pp);\n XYZpersp(UV(2, pp), UV(1, pp), 1) = XYZ(1, pp);\n XYZpersp(UV(2, pp), UV(1, pp), 2) = XYZ(2, pp);\n XYZpersp(UV(2, pp), UV(1, pp), 3) = XYZ(3, pp);\n check_norm(UV(2, pp), UV(1, pp)) = UV_norm(pp);\n end\nend\n\nRGBpersp = uint8(RGBpersp);\n\n\n\nend\n\n", "meta": {"author": "HajimeTaira", "repo": "InLoc_demo", "sha": "b4c42de09d288f35e65ec0156608c704d6176b4f", "save_path": "github-repos/MATLAB/HajimeTaira-InLoc_demo", "path": "github-repos/MATLAB/HajimeTaira-InLoc_demo/InLoc_demo-b4c42de09d288f35e65ec0156608c704d6176b4f/functions/wustl_function/ht_Points2Persp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754471, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3965486617942024}}
{"text": "load camera_results;\n\nstring_global = 'global n_ima';\nfor kk = 1:n_ima,\n string_global = [string_global ' x_' num2str(kk) ' X_' num2str(kk) ' xproj_' num2str(kk) ' x_proj_' num2str(kk)];\nend;\neval(string_global); \n\n\n%----------------- global optimization: ---------------------\n\nload projector_data; % load the projector corners (previously saved)\nload projector_results;\n\nsolution_projector = solution;\n\n\nload camera_results;\n\nsolution_camera = solution;\n\nparam_cam = solution_camera([1:10 16:end]);\nparam_proj = solution_projector([1:10 16:end]);\n\nparam = [param_cam;param_proj];\n\n\n% Restart the minimization from here (if need be):\nload camera_results;\nload calib_cam_proj_optim2;\n\n\noptions = [1 1e-4 1e-4 1e-6 0 0 0 0 0 0 0 0 0 12000 0 1e-8 0.1 0];\n\n%if 0, % use the full distortion model:\n \n% fprintf(1,'Take the complete distortion model\\n');\n\n % test the global error function:\n% e_global = error_cam_proj(param);\n \n% param_init = param;\n \n% param = leastsq('error_cam_proj',param,options);\n \n \n%else\n \n % Use a limitd distortion model (no 6th order)\n fprintf(1,'Take the 6th order distortion coefficient out\\n');\n \n param = param([1:9 11:11+6*n_ima-1 11+6*n_ima:11+6*n_ima+9-1 11+6*n_ima+9+1:end]);\n \n % test the global error function:\n e_global2 = error_cam_proj2(param);\n \n param_init = param;\n \n param = leastsq('error_cam_proj2',param,options);\n \n param = [param(1:9);0;param(10:10+6*n_ima-1);param(10+6*n_ima:10+6*n_ima+9-1);0;param(10+6*n_ima+9:end)];\n \n%end;\n\n\n\n\n% Extract the parameters:\n\ncam_proj_extract_param;\n\n \n% Relative prosition of camera wrt world:\nomc = omc_1;\nRc = Rc_1;\nTc = Tc_1;\n\n% relative position of projector wrt world:\nRp = R*Rc;\nomp = rodrigues(Rp);\nTp = T + R*Tc;\n\neval(['save calib_cam_proj_optim3 R om T fc fp cc cp alpha_c alpha_p kc kp Rc Rp Tc Tp omc omp param param_init']);\n\nno_image = 0;\n% Image size: (may or may not be available)\nnx = 640;\nny = 480;\n\ncomp_error_calib;\n\n% Save the optimal camera parameters:\nsaving_calib;\ncopyfile('Calib_Results.mat','camera_results_optim3.mat');\ndelete('Calib_Results.mat');\n\n% Save the optimal camera parameters:\nfc = fp;\ncc = cp;\nalpha_c = alpha_p;\nkc = kp;\n\nn_ima = 1;\nX_1 = X_proj;\nx_1 = x_proj;\nomc_1 = om;\nTc_1 = T;\nRc_1 = R;\n\n% Image size: (may or may not be available)\nnx = 1024;\nny = 768;\n\n% No calibration image is available (only the corner coordinates)\nno_image = 1;\n\ncomp_error_calib;\n\nsaving_calib;\ncopyfile('Calib_Results.mat','projector_results_optim3.mat');\ndelete('Calib_Results.mat');\n\n", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/EKF_monoSLAM_1pRANSAC/matlab_code/matlabcalibration2ourcalibration/TOOLBOX_calib/cam_proj_calib_optim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597974, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.39654865593273664}}
{"text": "function plot_q4_mesh ( node_num, element_num, node_xy, element_node, ...\n node_show, element_show, output_filename )\n\n%*****************************************************************************80\n%\n%% TPLOT_Q4_MESH plots a Q4 mesh.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 March 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NODE_NUM, the number of nodes.\n%\n% Input, real NODE_XY(2,NODE_NUM), the nodes.\n%\n% Input, integer ELEMENT_NUM, the number of elements.\n%\n% Input, integer ELEMENT_NODE(4,ELEMENT_NUM), the nodes \n% that form the elements.\n%\n% Input, logical NODE_SHOW:\n% 0, do not show the nodes.\n% 1, show the nodes.\n% 2, show the nodes, and label them.\n%\n% Input, logical ELEMENT_SHOW, \n% 0, do not show the elements.\n% 1, show the elements.\n% 2, show the elements, and label them.\n%\n% Input, string OUTPUT_FILENAME, the name of the output file.\n%\n element_order = 4;\n\n x_ps_max = 576;\n x_ps_max_clip = 594;\n x_ps_min = 36;\n x_ps_min_clip = 18;\n y_ps_max = 666;\n y_ps_max_clip = 684;\n y_ps_min = 126;\n y_ps_min_clip = 108;\n\n date_time = timestring ( );\n%\n% We need to do some figuring here, so that we can determine\n% the range of the data, and hence the height and width\n% of the piece of paper.\n%\n x_max = max ( node_xy(1,1:node_num) );\n x_min = min ( node_xy(1,1:node_num) );\n x_scale = x_max - x_min;\n \n x_max = x_max + 0.05 * x_scale;\n x_min = x_min - 0.05 * x_scale;\n x_scale = x_max - x_min;\n\n y_max = max ( node_xy(2,1:node_num) );\n y_min = min ( node_xy(2,1:node_num) );\n y_scale = y_max - y_min;\n\n y_max = y_max + 0.05 * y_scale;\n y_min = y_min - 0.05 * y_scale;\n y_scale = y_max - y_min;\n\n if ( x_scale < y_scale )\n\n delta = round ( ( x_ps_max - x_ps_min ) ...\n * ( y_scale - x_scale ) / ( 2.0 * y_scale ) );\n\n x_ps_max = x_ps_max - delta;\n x_ps_min = x_ps_min + delta;\n\n x_ps_max_clip = x_ps_max_clip - delta;\n x_ps_min_clip = x_ps_min_clip + delta;\n\n x_scale = y_scale;\n\n elseif ( y_scale < x_scale )\n\n delta = round ( ( y_ps_max - y_ps_min ) ...\n * ( x_scale - y_scale ) / ( 2.0 * x_scale ) );\n\n y_ps_max = y_ps_max - delta;\n y_ps_min = y_ps_min + delta;\n\n y_ps_max_clip = y_ps_max_clip - delta;\n y_ps_min_clip = y_ps_min_clip + delta;\n\n y_scale = x_scale;\n\n end\n%\n% Plot the mesh.\n%\n file_unit = fopen ( output_filename, 'wt' );\n\n if ( file_unit < 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PLOT_Q4_MESH - Fatal error!\\n' );\n fprintf ( 1, ' Could not open the output file.\\n' );\n error ( 'PLOT_Q4_MESH - Fatal error!' );\n end\n\n fprintf ( file_unit, '%%!PS-Adobe-3.0 EPSF-3.0\\n' );\n fprintf ( file_unit, '%%%%Creator: plot_q4_mesh.m\\n' );\n fprintf ( file_unit, '%%%%Title: %s\\n', output_filename );\n fprintf ( file_unit, '%%%%CreationDate: %s\\n', date_time );\n fprintf ( file_unit, '%%%%Pages: 1\\n' );\n fprintf ( file_unit, '%%%%BoundingBox: %d %d %d %d\\n', ...\n x_ps_min, y_ps_min, x_ps_max, y_ps_max );\n fprintf ( file_unit, '%%%%Document-Fonts: Times-Roman\\n' );\n fprintf ( file_unit, '%%%%LanguageLevel: 1\\n' );\n fprintf ( file_unit, '%%%%EndComments\\n' );\n fprintf ( file_unit, '%%%%BeginProlog\\n' );\n fprintf ( file_unit, '/inch {72 mul} def\\n' );\n fprintf ( file_unit, '%%%%EndProlog\\n' );\n fprintf ( file_unit, '%%%%Page: 1 1\\n' );\n fprintf ( file_unit, 'save\\n' );\n fprintf ( file_unit, '%%\\n' );\n fprintf ( file_unit, '%% Set the RGB color to very light gray.\\n' );\n fprintf ( file_unit, '%%\\n' );\n fprintf ( file_unit, '0.900 0.900 0.900 setrgbcolor\\n' );\n fprintf ( file_unit, '%%\\n' );\n fprintf ( file_unit, '%% Draw a gray border around the page.\\n' );\n fprintf ( file_unit, '%%\\n' );\n fprintf ( file_unit, 'newpath\\n' );\n fprintf ( file_unit, ' %d %d moveto\\n', x_ps_min, y_ps_min );\n fprintf ( file_unit, ' %d %d lineto\\n', x_ps_max, y_ps_min );\n fprintf ( file_unit, ' %d %d lineto\\n', x_ps_max, y_ps_max );\n fprintf ( file_unit, ' %d %d lineto\\n', x_ps_min, y_ps_max );\n fprintf ( file_unit, ' %d %d lineto\\n', x_ps_min, y_ps_min );\n fprintf ( file_unit, 'stroke\\n' );\n fprintf ( file_unit, '%%\\n' );\n fprintf ( file_unit, '%% Set the RGB color to black.\\n' );\n fprintf ( file_unit, '%%\\n' );\n fprintf ( file_unit, '0.000 0.000 0.000 setrgbcolor\\n' );\n fprintf ( file_unit, '%%\\n' );\n fprintf ( file_unit, '%% Set the font and its size.\\n' );\n fprintf ( file_unit, '%%\\n' );\n fprintf ( file_unit, '/Times-Roman findfont\\n' );\n fprintf ( file_unit, '0.50 inch scalefont\\n' );\n fprintf ( file_unit, 'setfont\\n' );\n fprintf ( file_unit, '%%\\n' );\n fprintf ( file_unit, '%% Print a title.\\n' );\n fprintf ( file_unit, '%%\\n' );\n fprintf ( file_unit, '%%210 702 moveto\\n' );\n fprintf ( file_unit, '%%(Triangulation) show\\n' );\n fprintf ( file_unit, '%%\\n' );\n fprintf ( file_unit, '%% Define a clipping polygon.\\n' );\n fprintf ( file_unit, '%%\\n' );\n fprintf ( file_unit, 'newpath\\n' );\n fprintf ( file_unit, ' %d %d moveto\\n', x_ps_min_clip, y_ps_min_clip );\n fprintf ( file_unit, ' %d %d lineto\\n', x_ps_max_clip, y_ps_min_clip );\n fprintf ( file_unit, ' %d %d lineto\\n', x_ps_max_clip, y_ps_max_clip );\n fprintf ( file_unit, ' %d %d lineto\\n', x_ps_min_clip, y_ps_max_clip );\n fprintf ( file_unit, ' %d %d lineto\\n', x_ps_min_clip, y_ps_min_clip );\n fprintf ( file_unit, 'clip newpath\\n' );\n%\n% Draw the nodes.\n%\n if ( node_num <= 200 )\n circle_size = 5;\n elseif ( node_num <= 500 )\n circle_size = 4;\n elseif ( node_num <= 1000 )\n circle_size = 3;\n elseif ( node_num <= 5000 )\n circle_size = 2;\n else\n circle_size = 1;\n end\n\n if ( 1 <= node_show )\n\n fprintf ( file_unit, '%%\\n' );\n fprintf ( file_unit, '%% Draw filled dots at the nodes.\\n' );\n fprintf ( file_unit, '%%\\n' );\n fprintf ( file_unit, '%% Set the RGB color to blue.\\n' );\n fprintf ( file_unit, '%%\\n' );\n fprintf ( file_unit, '0.000 0.150 0.750 setrgbcolor\\n' );\n fprintf ( file_unit, '%%\\n' );\n\n for node = 1 : node_num\n\n x_ps = floor ( ...\n ( ( x_max - node_xy(1,node) ) * x_ps_min ...\n + ( node_xy(1,node) - x_min ) * x_ps_max ) ...\n / ( x_max - x_min ) );\n\n y_ps = floor ( ...\n ( ( y_max - node_xy(2,node) ) * y_ps_min ...\n + ( node_xy(2,node) - y_min ) * y_ps_max ) ...\n / ( y_max - y_min ) );\n\n fprintf ( file_unit, ...\n ' newpath %d %d %d 0 360 arc closepath fill\\n', ...\n x_ps, y_ps, circle_size );\n\n end\n\n end\n%\n% Label the nodes.\n%\n if ( 2 <= node_show )\n \n fprintf ( file_unit, '%%\\n' );\n fprintf ( file_unit, '%% Label the nodes.\\n' );\n fprintf ( file_unit, '%%\\n' );\n fprintf ( file_unit, '%% Set the RGB color to darker blue.\\n' );\n fprintf ( file_unit, '%%\\n' );\n fprintf ( file_unit, '0.000 0.250 0.850 setrgbcolor\\n' );\n fprintf ( file_unit, '/Times-Roman findfont\\n' );\n fprintf ( file_unit, '0.20 inch scalefont\\n' );\n fprintf ( file_unit, 'setfont\\n' );\n fprintf ( file_unit, '%%\\n' );\n\n for node = 1 : node_num\n\n x_ps = floor ( ...\n ( ( x_max - node_xy(1,node) ) * x_ps_min ...\n + ( node_xy(1,node) - x_min ) * x_ps_max ) ...\n / ( x_max - x_min ) );\n\n y_ps = floor ( ...\n ( ( y_max - node_xy(2,node) ) * y_ps_min ...\n + ( node_xy(2,node) - y_min ) * y_ps_max ) ...\n / ( y_max - y_min ) );\n\n fprintf ( file_unit, ' %d %d moveto (%d) show\\n', ...\n x_ps, y_ps+5, node );\n\n end\n\n end\n%\n% Draw the elements.\n%\n if ( 1 <= element_show )\n\n fprintf ( file_unit, '%%\\n' );\n fprintf ( file_unit, '%% Set the RGB color to red.\\n' );\n fprintf ( file_unit, '%%\\n' );\n fprintf ( file_unit, '0.900 0.200 0.100 setrgbcolor\\n' );\n fprintf ( file_unit, '%%\\n' );\n fprintf ( file_unit, '%% Draw the elements.\\n' );\n fprintf ( file_unit, '%%\\n' );\n\n for element = 1 : element_num\n\n fprintf ( file_unit, 'newpath\\n' );\n\n for i = 1 : element_order + 1\n\n e = i4_wrap ( i, 1, element_order )\n\n node = element_node(e,element);\n\n x_ps = floor ( ...\n ( ( x_max - node_xy(1,node) ) * x_ps_min ...\n + ( node_xy(1,node) - x_min ) * x_ps_max ) ...\n / ( x_max - x_min ) );\n\n y_ps = floor ( ...\n ( ( y_max - node_xy(2,node) ) * y_ps_min ...\n + ( node_xy(2,node) - y_min ) * y_ps_max ) ...\n / ( y_max - y_min ) );\n\n if ( i == 1 )\n fprintf ( file_unit, ' %d %d moveto\\n', x_ps, y_ps );\n else\n fprintf ( file_unit, ' %d %d lineto\\n', x_ps, y_ps );\n end\n\n end\n\n fprintf ( file_unit, 'stroke\\n' );\n\n end\n\n end\n%\n% Label the elements.\n%\n if ( 2 <= element_show )\n \n fprintf ( file_unit, '%%\\n' );\n fprintf ( file_unit, '%% Label the elements.\\n' );\n fprintf ( file_unit, '%%\\n' );\n fprintf ( file_unit, '%% Set the RGB color to darker red.\\n' );\n fprintf ( file_unit, '%%\\n' );\n fprintf ( file_unit, '0.950 0.250 0.150 setrgbcolor\\n' );\n fprintf ( file_unit, '/Times-Roman findfont\\n' );\n fprintf ( file_unit, '0.20 inch scalefont\\n' );\n fprintf ( file_unit, 'setfont\\n' );\n fprintf ( file_unit, '%%\\n' );\n\n for element = 1 : element_num\n\n ave_x = 0.0;\n ave_y = 0.0;\n\n for i = 1 : element_order\n \n node = element_node(i,element);\n ave_x = ave_x + node_xy(1,node);\n ave_y = ave_y + node_xy(2,node);\n end\n \n ave_x = ave_x / element_order;\n ave_y = ave_y / element_order;\n\n x_ps = floor ( ...\n ( ( x_max - ave_x ) * x_ps_min ...\n + ( ave_x - x_min ) * x_ps_max ) ...\n / ( x_max - x_min ) );\n\n y_ps = floor ( ...\n ( ( y_max - ave_y ) * y_ps_min ...\n + ( ave_y - y_min ) * y_ps_max ) ...\n / ( y_max - y_min ) );\n\n fprintf ( file_unit, ' %d %d moveto (%d) show\\n', ...\n x_ps, y_ps, element );\n\n end\n end\n\n fprintf ( file_unit, '%%\\n' );\n fprintf ( file_unit, 'restore showpage\\n' );\n fprintf ( file_unit, '%%\\n' );\n fprintf ( file_unit, '%% End of page.\\n' );\n fprintf ( file_unit, '%%\\n' );\n fprintf ( file_unit, '%%%%Trailer\\n' );\n fprintf ( file_unit, '%%%%EOF\\n' );\n\n fclose ( file_unit );\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/quad_mesh/plot_q4_mesh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370308082623216, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.3965257708659416}}
{"text": "function r = sup(a)\n%SUP right bound of point matrix (only for completeness)\n%\n% r = sup(a)\n%\n\n% written 10/16/98 S.M. Rump\n% modified 04/04/04 S.M. Rump set round to nearest for safety\n% modified 04/06/05 S.M. Rump rounding unchanged\n%\n\n r = a;\n ", "meta": {"author": "douthwja01", "repo": "OpenMAS", "sha": "962f321f82167db78066b2c88c783423ecc3b73a", "save_path": "github-repos/MATLAB/douthwja01-OpenMAS", "path": "github-repos/MATLAB/douthwja01-OpenMAS/OpenMAS-962f321f82167db78066b2c88c783423ecc3b73a/toolboxes/Intlab_V7.1/intval/sup.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.3965257708659416}}
{"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": "\nvI = cat(3, 85, 80, 217) / 255;\n\nvPhotoshopValues = [30; 98; 51; 73; 5; 53];\n\nvCoeffValues = (vPhotoshopValues - 50) ./ 50;\nvO = ApplyBlackWhiteFilter(vI, vCoeffValues);\nvO = max(min(vO, 1), 0);\n\nround(255 * vI(:))\nround(255 * vO(:))", "meta": {"author": "RoyiAvital", "repo": "StackExchangeCodes", "sha": "d2a934616995fa8a9f4df1ca29029402435b9e6f", "save_path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes", "path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes/StackExchangeCodes-d2a934616995fa8a9f4df1ca29029402435b9e6f/SignalProcessing/Q688/Analysis002.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.396522609765151}}
{"text": "function [frames, descrs] = vl_phow(im, varargin)\n% VL_PHOW Extract PHOW features\n% [FRAMES, DESCRS] = VL_PHOW(IM) extracts PHOW features [1] from the\n% image IM. PHOW is simply dense SIFT applied at several resolutions. This function is a commodity interface to VL_DSIFT() and\n% VL_IMSMOOTH().\n%\n% DESCRS has the same format of VL_SIFT() and VL_DSIFT(). FRAMES(1:2,:)\n% are the x,y coordinates of the center of each descriptor, FRAMES(3,:)\n% is the contrast of the descriptor, as returned by VL_DSIFT() (for\n% colour variant, contranst is computed on the intensity channel).\n% FRAMES(4,:) is the size of the bin of the descriptor.\n%\n% By default,\n% VL_PHOW() computes the gray-scale variant of the descriptor. The\n% COLOR option can be used to compute the color variant instead.\n%\n% Verbose:: false\n% Set to true to turn on verbose output.\n%\n% Sizes:: [4 6 8 10]\n% Scales at which the dense SIFT features are extracted. Each\n% value is used as bin size for the VL_DSIFT() function.\n%\n% Fast:: true\n% Set to false to turn off the fast SIFT features computation by\n% VL_DSIFT().\n%\n% Step:: 2\n% Step (in pixels) of the grid at which the dense SIFT features\n% are extracted.\n%\n% Color:: 'gray'\n% Choose between 'gray' (PHOW-gray), 'rgb', 'hsv', and 'opponent'\n% (PHOW-color).\n%\n% ContrastThreshold:: 0.005\n% Contrast threshold below which SIFT features are mapped to\n% zero. The input image is scaled to have intensity range in [0,1]\n% (rather than [0,255]) and this value is compared to the\n% descriptor norm as returned by VL_DSIFT().\n%\n% WindowSize:: 1.5\n% Size of the Gaussian window in units of spatial bins.\n%\n% Magnif:: 6\n% The image is smoothed by a Gaussian kernel of standard deviation\n% SIZE / MAGNIF. Note that, in the standard SIFT descriptor, the\n% magnification value is 3; here the default one is 6 as it seems\n% to perform better in applications.\n%\n% FloatDescriptors:: false\n% If set to TRUE, the descriptors are returned in floating point\n% format.\n%\n% See also: VL_DSIFT(), VL_HELP().\n\n% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\n% -------------------------------------------------------------------\n% Parse the arguments\n% -------------------------------------------------------------------\n\n opts.verbose = false ;\n opts.fast = true ;\n opts.sizes = [4 6 8 10] ;\n opts.step = 2 ;\n opts.color = 'gray' ;\n opts.floatdescriptors = false ;\n opts.magnif = 6 ;\n opts.windowsize = 1.5 ;\n opts.contrastthreshold = 0.005 ;\n opts = vl_argparse(opts,varargin) ;\n\n dsiftOpts = {'norm', 'windowsize', opts.windowsize} ;\n if opts.verbose, dsiftOpts{end+1} = 'verbose' ; end\n if opts.fast, dsiftOpts{end+1} = 'fast' ; end\n if opts.floatdescriptors, dsiftOpts{end+1} = 'floatdescriptors' ; end\n dsiftOpts(end+(1:2)) = {'step', opts.step} ;\n\n% -------------------------------------------------------------------\n% Extract the features\n% -------------------------------------------------------------------\n\n\n % standarize the image\n imageSize = [size(im,2) ; size(im,1)] ;\n if strcmp(lower(opts.color), 'gray')\n numChannels = 1 ;\n if size(im,3) > 1, im = rgb2gray(im) ; end\n else\n numChannels = 3 ;\n if size(im,3) == 1, im = cat(3, im, im, im) ; end\n switch lower(opts.color)\n case 'rgb'\n case 'opponent'\n % Note that the mean differs from the standard definition of opponent\n % space and is the regular intesity (for compatibility with\n % the contrast thresholding).\n %\n % Note also that the mean is added pack to the other two\n % components with a small multipliers for monochromatic\n % regions.\n mu = 0.3*im(:,:,1) + 0.59*im(:,:,2) + 0.11*im(:,:,3) ;\n alpha = 0.01 ;\n im = cat(3, mu, ...\n (im(:,:,1) - im(:,:,2))/sqrt(2) + alpha*mu, ...\n (im(:,:,1) + im(:,:,2) - 2*im(:,:,3))/sqrt(6) + alpha*mu) ;\n case 'hsv'\n im = rgb2hsv(im) ;\n otherwise\n opts.color = 'hsv' ;\n warning('Color space not recongized, defaulting to HSV color space.') ;\n end\n end\n\n if opts.verbose\n fprintf('%s: color space: %s\\n', mfilename, opts.color) ;\n fprintf('%s: image size: %d x %d\\n', mfilename, imageSize(1), imageSize(2)) ;\n fprintf('%s: sizes: [%s]\\n', mfilename, sprintf(' %d', opts.sizes)) ;\n end\n\n for si = 1:length(opts.sizes)\n\n % Recall from VL_DSIFT() that the first descriptor for scale SIZE has\n % center located at XC = XMIN + 3/2 SIZE (the Y coordinate is\n % similar). It is convenient to align the descriptors at different\n % scales so that they have the same geometric centers. For the\n % maximum size we pick XMIN = 1 and we get centers starting from\n % XC = 1 + 3/2 MAX(OPTS.SIZES). For any other scale we pick XMIN so\n % that XMIN + 3/2 SIZE = 1 + 3/2 MAX(OPTS.SIZES).\n %\n % In pracrice, the offset must be integer ('bounds'), so the\n % alignment works properly only if all OPTS.SZES are even or odd.\n\n off = floor(1 + 3/2 * (max(opts.sizes) - opts.sizes(si))) ;\n\n % smooth the image to the appropriate scale based on the size\n % of the SIFT bins\n sigma = opts.sizes(si) / opts.magnif ;\n ims = vl_imsmooth(im, sigma) ;\n\n % extract dense SIFT features from all channels\n for k = 1:numChannels\n [f{k}, d{k}] = vl_dsift(...\n ims(:,:,k), ...\n dsiftOpts{:}, ...\n 'size', opts.sizes(si), ...\n 'bounds', [off off +inf +inf]) ;\n end\n\n % remove low contrast descriptors\n % note that for color descriptors the V component is\n % thresholded\n switch lower(opts.color)\n case {'gray', 'opponent'}\n contrast = f{1}(3,:) ;\n case 'rgb'\n contrast = mean([f{1}(3,:) ; f{2}(3,:) ; f{3}(3,:)],1) ;\n otherwise % hsv\n contrast = f{3}(3,:) ;\n end\n for k = 1:numChannels\n d{k}(:, contrast < opts.contrastthreshold) = 0 ;\n end\n\n % save only x,y, and the scale\n frames{si} = [f{1}(1:3, :) ; opts.sizes(si) * ones(1,size(f{1},2))] ;\n descrs{si} = cat(1, d{:}) ;\n end\n descrs = cell2mat(descrs) ;\n frames = cell2mat(frames) ;\nend\n", "meta": {"author": "yihui-he", "repo": "panorama", "sha": "0c993d4ba6780dcb175b2c1fc7d25b513b7bb39b", "save_path": "github-repos/MATLAB/yihui-he-panorama", "path": "github-repos/MATLAB/yihui-he-panorama/panorama-0c993d4ba6780dcb175b2c1fc7d25b513b7bb39b/lib/vlfeat-0.9.20/toolbox/sift/vl_phow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.3964229975143914}}
{"text": "%DEMOIMAGEGRAPHS One-line description here, please.\n%\n% output = demoImageGraphs(input)\n%\n% Example\n% demoImageGraphs\n%\n% See also\n%\n \n% ------\n% Author: David Legland\n% e-mail: david.legland@inrae.fr\n% INRAE - BIA Research Unit - BIBS Platform (Nantes)\n% Created: 2022-04-01, using Matlab 9.12.0.1884302 (R2022a)\n% Copyright 2022 INRAE.\n\n% create a simple 2D binary image\n\nlx = -10:10;\nly = -10:10;\n[x, y] = meshgrid(lx, ly);\nimg = hypot(x, y) < 8.5;\n\nfigure; \nimshow(img, 'InitialMagnification', 1000);\nprint(gcf, 'sample_image.png', '-dpng');\n\n% create adjacency graph\n\n[v, e] = imageGraph(img);\nfigure; imshow(ones(size(img)), 'InitialMagnification', 1000);\nhold on; drawGraph(v, e);\nprint(gcf, 'imageGraph_2d.png', '-dpng');\n\n% create boundary graph\n\n[v, e] = imageBoundaryGraph(img);\nfigure; imshow(ones(size(img)), 'InitialMagnification', 1000);\nhold on; drawGraphEdges(v, e, 'Color', 'b', 'LineWidth', 2);\nprint(gcf, 'imageBoundaryGraph_2d.png', '-dpng');\n\n% save into figure\nprint(gcf, 'image_graphs_2d.png', '-dpng');", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/docs/matGeom-manual/images/graphs/images/demoImageGraphs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.3964229896904785}}
{"text": "function varargout = parseMeshData(varargin)\n%PARSEMESHDATA Conversion of data representation for meshes.\n%\n% MESH = parseMeshData(VERTICES, FACES)\n% MESH = parseMeshData(VERTICES, EDGES, FACES)\n% Returns the mesh info into a single structure with fields \"vertices\",\n% \"edges\" and \"faces\".\n%\n% [VERTICES, FACES] = parseMeshData(MESH)\n% Returns the mesh info into two output variables containing coordinates\n% of vertices (as a Nv_by_3 array) and the list of vertex indices for\n% each face (either as a Nf-by-3 or Nf-by-4 int array, or as a cell\n% array).\n%\n% [VERTICES, EDGES, FACES] = parseMeshData(MESH)\n% Also returns the vertex indices of each edge, as a Ne-by-2 array of\n% vertex indices.\n%\n% See also \n% meshes3d, formatMeshOutput\n%\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@inra.fr\n% Created: 2010-12-06, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2010-2022 INRA - Cepia Software Platform\n\n% initialize edges to empty variable\nedges = [];\n\n% Process input arguments\nswitch nargin\n case 1\n % input is a data structure\n mesh = varargin{1};\n vertices = mesh.vertices;\n faces = mesh.faces;\n if isfield(mesh, 'edges')\n edges = mesh.edges;\n end\n \n case 2\n % input are vertices and faces\n vertices = varargin{1};\n faces = varargin{2};\n \n case 3\n % input are vertices, edges and faces\n vertices = varargin{1};\n edges = varargin{2};\n faces = varargin{3};\n \n otherwise\n error('Wrong number of arguments');\nend\n\n% returns either a struct or several variables\nvarargout = formatMeshOutput(nargout, vertices, edges, faces);\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/meshes3d/private/parseMeshData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.39642298577852203}}
{"text": "function [ y, symm ] = cvx_s_sparse( m, n, symm, i, j )\n\n%CVX_S_SPARSE Matrices with a fixed sparsity pattern.\n\nif nargin < 5,\n error( 'Sparsity structure missing.' );\nelseif ~isnumeric( i ) || ~isnumeric( j ),\n error( 'Sparsity arguments must be vectors of nonnegative integers.' );\nelseif any( i <= 0 ) || any( j <= 0 ) || any( i ~= floor( i ) ) || any( j ~= floor( j ) ),\n error( 'Sparsity arguments must be vectors nonnegative integers.' );\nelseif numel( i ) ~= 1 && numel( j ) ~= 1 && numel( i ) ~= numel( j ),\n error( 'Sparsity arguments have incompatible size.' );\nelseif any( i > m ) || any( j > n ),\n error( 'One or more indices are out of range.' );\nelseif symm && m ~= n,\n error( 'Symmetric structure requires a square matrix.' );\nend\ni = i(:); \nj = j(:);\nnz = max( numel(i), numel(j) );\nif symm,\n t = max(i,j);\n j = min(i,j);\n i = t;\nend\n[ c, cndxs ] = sort( i + ( j - 1 ) * m );\ntt = [true;c(2:end)~=c(1:end-1)];\nc = c(tt);\nr = 1 : length(c);\nif symm,\n if numel(i) > 1,\n i = i(cndxs(tt));\n end\n if numel(j) > 1,\n j = j(cndxs(tt));\n end\n tt = i ~= j;\n r = [ r , r(tt) ];\n c = [ c ; j(tt) + ( i(tt) - 1 ) * m ];\nend\ny = min( sparse( r, c, 1, nz, m * n ), 1 );\nsymm = false;\n\n% Copyright 2005-2016 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": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/structures/cvx_s_sparse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.39642298186656544}}
{"text": "%% Image Warping\n% A demo program shows how perspective transformation applied on an image.\n% Based on a sample code from\n% .\n%\n% Sources:\n%\n% * \n%\n\nfunction varargout = warp_perspective_demo_gui(im)\n % load source image and set initial ROI corners (4 points clockwise)\n roi = [];\n if nargin < 1\n if true\n im = fullfile(mexopencv.root(), 'test', 'books_right.jpg');\n roi = [360 109; 532 138; 460 417; 317 338];\n else\n im = fullfile(mexopencv.root(), 'test', 'box_in_scene.png');\n roi = [243 188; 328 151; 388 294; 319 351];\n end\n img = cv.imread(im, 'Color',true);\n elseif ischar(im)\n img = cv.imread(im, 'Color',true);\n else\n img = im;\n end\n if isempty(roi)\n roi = bsxfun(@rdivide, [size(img,2) size(img,1)], ...\n [1.7 4.2; 1.15 3.32; 1.33 1.1; 1.93 1.36]);\n end\n\n % create the UI and hook event handlers\n h = buildGUI(img, roi);\n if nargout > 0, varargout{1} = h; end\n opts = {'Interruptible','off', 'BusyAction','cancel'};\n set(h.fig, 'CloseRequestFcn',@(~,~) delete(h.fig), ...\n 'WindowKeyPressFcn',@onType, opts{:});\n set(h.fig(1), 'WindowButtonDownFcn',@onMouseDown, opts{:});\n\n\n %% Callback Functions\n\n function redraw()\n %REDRAW Apply transformation using current ROI and display results\n\n % reapply transformation\n out1 = drawROI(img, roi);\n [out2, sz] = warpROI(img, roi);\n\n % show results and ajust second plot to fit image\n set(h.img(1), 'CData',out1);\n set(h.img(2), 'CData',out2, 'XData',[1 sz(1)], 'YData',[1 sz(2)]);\n set(h.ax(2), 'XLim',[0 sz(1)]+0.5, 'YLim',[0 sz(2)]+0.5);\n pos = get(h.fig(2), 'Position');\n set(h.fig(2), 'Position',[pos(1:2) sz]);\n drawnow;\n end\n\n function onType(~,e)\n %ONTYPE Event handler for key press on figure\n\n switch e.Key\n case 'h'\n helpdlg({\n 'Use your mouse to select a point and move it'\n 'to see transformation changes.'\n ''\n 'Hot keys:'\n 'h - this help dialog'\n 'q - quit the program'\n 'r - change order of points to rotate transformation'\n 'i - change order of points to invert transformation '\n });\n case {'q', 'escape'}\n close(h.fig);\n case 'r'\n roi = circshift(roi, -1);\n redraw();\n case 'i'\n roi = roi([2 1 4 3],:);\n redraw();\n end\n end\n\n function onMouseDown(~,~)\n %ONMOUSEDOWN Event handler for mouse down on figure\n\n % hit-test for closest ROI corner\n pt = getCurrentPoint(h.ax(1));\n d = sum(abs(bsxfun(@minus, roi, pt)), 2);\n [mn, pt_idx] = min(d);\n if mn < 20\n % attach event handlers, and change mouse pointer\n set(h.fig(1), 'Pointer','cross', ...\n 'WindowButtonMotionFcn',{@onMouseMove, pt_idx}, ...\n 'WindowButtonUpFcn',@onMouseUp);\n end\n end\n\n function onMouseMove(~,~,idx)\n %ONMOUSEMOVE Event handler for mouse move on figure\n\n % move specified ROI corner\n pt = getCurrentPoint(h.ax(1));\n roi(idx,:) = pt;\n redraw();\n end\n\n function onMouseUp(~,~)\n %ONMOUSEUP Event handler for mouse up on figure\n\n % detach event handlers, and restore mouse pointer\n set(h.fig(1), 'Pointer','arrow', ...\n 'WindowButtonMotionFcn','', ...\n 'WindowButtonUpFcn','');\n end\nend\n\n%% Helper Functions\n\nfunction out = drawROI(img, pts)\n %DRAWROI Show ROI corners with labels\n\n labels = {'TL', 'TR', 'BR', 'BL'};\n out = cv.polylines(img, pts, 'Closed',true, 'Color',[0 0 255], 'Thickness',2);\n out = cv.circle(out, pts, 5, 'Color',[0 255 0], 'Thickness',3);\n out = cv.putText(out, labels, pts, ...\n 'FontScale',0.8, 'Color',[255 0 0], 'Thickness',2);\nend\n\nfunction [out, dsz] = warpROI(img, srcPts)\n %WARPROI Compute warped image from ROI\n\n % map ROI corners to corresponding destination rectangle\n len = diff(srcPts([1:end 1],:), 1, 1); % [TR-TL; BR-TR; BL-BR; TL-BL]\n len = cellfun(@norm, num2cell(len, 2)); % lengths of sides\n w = max(len(1), len(3));\n h = max(len(2), len(4));\n dstPts = [0 0; w 0; w h; 0 h];\n\n % compute homography between points and apply persepective transformation\n dsz = round([w h]);\n H = cv.findHomography(srcPts, dstPts);\n out = cv.warpPerspective(img, H, 'DSize',dsz);\nend\n\nfunction p = getCurrentPoint(ax)\n %GETCURRENTPOINT Retrieve current mouse location\n\n p = get(ax, 'CurrentPoint');\n p = p(1,1:2) - 1;\nend\n\nfunction h = buildGUI(img, roi)\n %BUILDGUI Creates the UI\n\n % apply initial perspective transformation\n out1 = drawROI(img, roi);\n out2 = warpROI(img, roi);\n sz1 = size(out1);\n sz2 = size(out2);\n\n % properties\n fprops = {'Menubar','none', 'Resize','on'};\n aprops = {'Units','normalized', 'Position',[0 0 1 1]};\n h = struct();\n\n % show input image + ROI corners\n h.fig(1) = figure('Name','Image', ...\n 'Position',[100 200 sz1(2) sz1(1)], fprops{:});\n h.ax(1) = axes('Parent',h.fig(1), aprops{:});\n if mexopencv.isOctave()\n h.img(1) = imshow(out1);\n else\n h.img(1) = imshow(out1, 'Parent',h.ax(1));\n end\n\n % show warped image\n h.fig(2) = figure('Name','Warped', ...\n 'Position',[200+sz1(2) 200 sz2(2) sz2(1)], fprops{:});\n h.ax(2) = axes('Parent',h.fig(2), aprops{:});\n if mexopencv.isOctave()\n h.img(2) = imshow(out2);\n else\n h.img(2) = imshow(out2, 'Parent',h.ax(2));\n end\nend\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/samples/warp_perspective_demo_gui.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.3964129406207689}}
{"text": "function Data = normalize_data ( Data, options )\n\nn = length(Data);\n\n%% noramlizing the first image\nshape = normalize_first_shape( Data(1) , options );\nData(1).shape = shape;\n\n%% using the first to noramlizing others.\nfor i = 2 : n\n [shape] = normalize_rest_shape( Data(1), Data(i), options );\n Data(i).shape = shape;\nend\n\nend", "meta": {"author": "tntrung", "repo": "sdm_face_alignment", "sha": "f546cbb1e77b8bad971e8c5914d2ca73e0bb9b67", "save_path": "github-repos/MATLAB/tntrung-sdm_face_alignment", "path": "github-repos/MATLAB/tntrung-sdm_face_alignment/sdm_face_alignment-f546cbb1e77b8bad971e8c5914d2ca73e0bb9b67/common/align/normalize_data.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.39641293212969425}}
{"text": "% given 3D point set of face, draw structure of face in 3D space, or\n% given 2D reprojection point set of face, draw it in corresponding image\nfunction drawFace(KeyPointSet, showKpsIdx)\n% KeyPointSet - 66x2 or 66x3\n\n dim = size(KeyPointSet, 2);\n \n % 9 sets of keypoints(outlines) to be draw using line function\n sets = {0:16; 17:21; 22:26; 27:30; 31:35;... % face, eyebrows(r,l), nose(t,b)\n [36:41 36]; [42:47 42]; [48:59 48]; [48, 60:62, 54, 63:65, 48]}; % eyes(r,l), mouth(o,i)\n % notice: 0 indexed here\n\n % draw connections\n for i = 1:size(sets,1)\n indices = sets{i} + 1; % convert to 1-indexed\n if dim == 3\n line(KeyPointSet(indices, 1), KeyPointSet(indices, 2), KeyPointSet(indices, 3)...\n , 'Color', [0 150 230]/255, 'LineWidth', 3);\n elseif dim == 2\n line(KeyPointSet(indices, 1), KeyPointSet(indices, 2), 'Color', [0 150 230]/255, 'LineWidth', 2);\n end\n end\n \n hold on\n \n % draw kps\n if dim == 3\n scatter3(KeyPointSet(:,1), KeyPointSet(:,2), KeyPointSet(:,3), 500, 'r.');\n if showKpsIdx\n text(KeyPointSet(:,1), KeyPointSet(:,2), KeyPointSet(:,3), num2str((0 : 65)'));\n end\n elseif dim == 2\n scatter(KeyPointSet(:,1), KeyPointSet(:,2), 200, 'r.');\n if showKpsIdx\n text(KeyPointSet(:,1), KeyPointSet(:,2), num2str((0 : 65)'));\n end\n end\nend\n\n\n", "meta": {"author": "zhixuany", "repo": "HUMBI", "sha": "7b03af54ea5bd7e5e21e43026b51888403f995db", "save_path": "github-repos/MATLAB/zhixuany-HUMBI", "path": "github-repos/MATLAB/zhixuany-HUMBI/HUMBI-7b03af54ea5bd7e5e21e43026b51888403f995db/face/drawFace.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.39641293212969425}}
{"text": "function datapt = lvd_AeroTasks(stateLogEntry, subTask, dummy)\n%lvd_AeroTasks Summary of this function goes here\n% Detailed explanation goes here\n arguments\n stateLogEntry(1,1) LaunchVehicleStateLogEntry\n subTask(1,:) char\n dummy\n end\n\n ut = stateLogEntry.time;\n rVect = stateLogEntry.position;\n vVect = stateLogEntry.velocity;\n bodyInfo = stateLogEntry.centralBody;\n mass = stateLogEntry.getTotalVehicleMass();\n aero = stateLogEntry.aero;\n attState = stateLogEntry.attitude;\n celBodyData = bodyInfo.celBodyData;\n \n maStateLogEntry = [ut, rVect(:)', vVect(:)', bodyInfo.id, mass, 0, 0, 0, -1];\n altitude = ma_GALongLatAltTasks(maStateLogEntry, 'alt', celBodyData);\n vVectEcefMag = ma_GALongLatAltTasks(maStateLogEntry, 'bodyFixedVNorm', celBodyData);\n [lat, long, ~, ~, ~, ~, ~, ~] = getLatLongAltFromInertialVect(ut, rVect, bodyInfo, vVect);\n [density, pressureKPA, ~] = getAtmoDensityAtAltitude(bodyInfo, altitude, lat, ut, long); \n [~,angOfAttack,angOfSideslip,totalAoA] = attState.getAeroAngles(ut, rVect, vVect, bodyInfo);\n\n switch subTask \n case 'dragCoeff'\n datapt = stateLogEntry.aero.getDragCoeff(ut, rVect, vVect, bodyInfo, mass, altitude, pressureKPA, density, vVectEcefMag, totalAoA, angOfAttack, angOfSideslip);\n case 'dragForce'\n dragForceModel = DragForceModel();\n dragForceVect = dragForceModel.getForce(ut, rVect, vVect, mass, bodyInfo, aero, [], [], [], [], [], [], [], [], [], [], attState);\n dragForceMag = norm(dragForceVect); %mT*km/s^2\n datapt = dragForceMag*1000; %kN\n end\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/ksptot_lvd/process_data/GraphicalAnalysis/tasks/lvd_AeroTasks.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3963671847306774}}
{"text": "function out = calcGrainVotes(job,varargin)\n% compute votes from grain boundaries\n%\n% Syntax\n%\n% % compute votes from all p2c and c2c boundaries\n% job.calcGBVotes('threshold', 2*degree)\n%\n% % compute votes only from p2c boundaries -> growth algorithm\n% job.calcGBVotes('p2c', 'threshold', 3*degree, 'tol', 1.5*degree)\n%\n% Input\n% job - @parentGrainReconstructor\n%\n% Output\n% job.votes - table of votes\n%\n% Options\n% p2c - consider only parent / child grain boundaries\n% c2c - consider only child / child grain boundaries\n% threshold - threshold fitting angle between job.p2c and the boundary OR\n% tolerance - range over which the probability increases from 0 to 1 (default 1.5)\n% numFit - number of fits to be computed\n%\n\n% noOpt = ~check_option(varargin,{'p2c','c2c'});\n\nif nargin > 1 && isnumeric(varargin{1})\n id = varargin{1};\nelse\n id = job.grains.id;\nend\n\n% the original child orientation\nori = job.grainsPrior('id',id).meanOrientation;\n\n% all variants\noriV = variants(job.p2c, ori);\nnumV = size(oriV,2);\n\n% fit with neighboring grains\nA = job.grains('id',id).neighbors('matrix','maxId',max(job.grains.id));\nA = A(id,:);\n[grainInd,nId] = find(A);\ngrainInd = grainInd(:); nId = nId(:);\n\n% some neighbors coorespond to parent and some to child grains\nnInd = job.grains.id2ind(nId);\nisParent = job.grains.phaseId(nInd) == job.parentPhaseId;\noriP = job.grains(nInd(isParent)).meanOrientation;\n\nisChild = job.grains.phaseId(nInd) == job.childPhaseId;\noriChildV = variants(job.p2c,job.grains(nInd(isChild)).meanOrientation);\n\n% compute fits to all neighbors\nfit = nan(length(nId),numV);\nfor iV = 1:numV\n \n % parent - parent fit\n fit(isParent,iV) = angle(oriV(grainInd(isParent),iV), oriP);\n \n % parent - child fit\n %fit(isChild,iV) = min(angle(oriV(grainInd(isChild),iV), oriChildV),[],2);\n \nend\n\n% accumulate votes, i.e. compute a probability for each grain / parentId\n% combination\nvotes = accumVotes(repmat(grainInd,1,numV), repmat(1:numV,length(grainInd),1), fit,...\n max(grainInd), varargin{:});\n\n% output \nif nargin > 1 && isnumeric(varargin{1})\n out = votes;\nelse\n job.votes = votes; \n out = job;\nend\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/EBSDAnalysis/@parentGrainReconstructor/calcGrainVotes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.39636717940513666}}
{"text": "function gr_test07 ( node_num, node_coordinates, edge_num, edge_nodes );\n\n%*****************************************************************************80\n%\n%% GR_TEST07 tests GR_INCIDENCE_MATRIX.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 January 2011\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'GR_TEST07:\\n' );\n fprintf ( 1, ' GR_INCIDENCE_MATRIX computes the incidence matrix.\\n' );\n\n incidence_matrix = gr_incidence_matrix ( node_num, node_coordinates, ...\n edge_num, edge_nodes );\n\n i4mat_print ( edge_num, node_num, incidence_matrix, ...\n ' The incidence matrix:' );\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/graph_representation/gr_test07.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.3963671794051366}}
{"text": "function r8mat_print ( m, n, a, title )\n\n%*****************************************************************************80\n%\n%% R8MAT_PRINT prints an R8MAT.\n%\n% Discussion:\n%\n% An R8MAT is an array of R8's.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the number of rows in A.\n%\n% Input, integer N, the number of columns in A.\n%\n% Input, real A(M,N), the matrix.\n%\n% Input, string TITLE, a title to be printed.\n%\n r8mat_print_some ( m, n, a, 1, 1, m, n, title );\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/table_io/r8mat_print.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.3963671740795958}}
{"text": "classdef BankAngleConstraint < AbstractConstraint\n %BankAngleConstraint Summary of this class goes here\n % Detailed explanation goes here\n \n properties\n normFact = 1;\n event LaunchVehicleEvent\n eventNode(1,1) ConstraintStateComparisonNodeEnum = ConstraintStateComparisonNodeEnum.FinalState;\n \n lb(1,1) double = 0;\n ub(1,1) double = 0;\n \n evalType(1,1) ConstraintEvalTypeEnum = ConstraintEvalTypeEnum.FixedBounds;\n stateCompType(1,1) ConstraintStateComparisonTypeEnum = ConstraintStateComparisonTypeEnum.Equals;\n stateCompEvent LaunchVehicleEvent\n stateCompNode(1,1) ConstraintStateComparisonNodeEnum = ConstraintStateComparisonNodeEnum.FinalState;\n end\n \n methods\n function obj = BankAngleConstraint(event, lb, ub)\n obj.event = event;\n obj.lb = lb;\n obj.ub = ub; \n \n obj.id = rand();\n end\n \n function [lb, ub] = getBounds(obj)\n lb = obj.lb;\n ub = obj.ub;\n end\n \n function [c, ceq, value, lwrBnd, uprBnd, type, eventNum, valueStateComp] = evalConstraint(obj, stateLog, celBodyData) \n type = obj.getConstraintType();\n \n switch obj.eventNode\n case ConstraintStateComparisonNodeEnum.FinalState\n stateLogEntry = stateLog.getLastStateLogForEvent(obj.event);\n \n case ConstraintStateComparisonNodeEnum.InitialState\n stateLogEntry = stateLog.getFirstStateLogForEvent(obj.event);\n \n otherwise\n error('Unknown event node.');\n end\n \n ut = stateLogEntry.time;\n rVect = stateLogEntry.position;\n vVect = stateLogEntry.velocity;\n bodyInfo = stateLogEntry.centralBody;\n \n [bankAng,~,~] = stateLogEntry.attitude.getAeroAngles(ut, rVect, vVect, bodyInfo);\n value = rad2deg(bankAng);\n \n if(obj.evalType == ConstraintEvalTypeEnum.StateComparison)\n switch obj.stateCompNode\n case ConstraintStateComparisonNodeEnum.FinalState\n stateLogEntryStateComp = stateLog.getLastStateLogForEvent(obj.stateCompEvent).deepCopy();\n\n case ConstraintStateComparisonNodeEnum.InitialState\n stateLogEntryStateComp = stateLog.getFirstStateLogForEvent(obj.stateCompEvent).deepCopy();\n\n otherwise\n error('Unknown event node.');\n end\n \n cartElem = stateLogEntryStateComp.getCartesianElementSetRepresentation();\n cartElem = cartElem.convertToFrame(stateLogEntry.centralBody.getBodyCenteredInertialFrame());\n stateLogEntryStateComp.setCartesianElementSet(cartElem);\n \n ut = stateLogEntryStateComp.time;\n rVect = stateLogEntryStateComp.position;\n vVect = stateLogEntryStateComp.velocity;\n bodyInfo = stateLogEntryStateComp.centralBody;\n\n [bankAng,~,~] = stateLogEntryStateComp.attitude.getAeroAngles(ut, rVect, vVect, bodyInfo);\n valueStateComp = rad2deg(bankAng);\n else\n valueStateComp = NaN;\n end\n \n [c, ceq] = obj.computeCAndCeqValues(value, valueStateComp); \n \n lwrBnd = obj.lb;\n uprBnd = obj.ub;\n \n eventNum = obj.event.getEventNum();\n end\n \n function sF = getScaleFactor(obj)\n sF = obj.normFact;\n end\n \n function setScaleFactor(obj, sF)\n obj.normFact = sF;\n end\n \n function tf = usesStage(obj, stage)\n tf = false;\n end\n \n function tf = usesEngine(obj, engine)\n tf = false;\n end\n \n function tf = usesTank(obj, tank)\n tf = false;\n end\n \n function tf = usesEngineToTankConn(obj, engineToTank)\n tf = false;\n end\n \n function tf = usesEvent(obj, event)\n tf = obj.event == event;\n if(obj.evalType == ConstraintEvalTypeEnum.StateComparison)\n tf = tf || obj.stateCompEvent == event;\n end\n end\n \n function tf = usesStopwatch(obj, stopwatch)\n tf = false;\n end\n \n function tf = usesExtremum(obj, extremum)\n tf = false;\n end\n \n function tf = canUseSparseOutput(obj)\n tf = true;\n end\n \n function event = getConstraintEvent(obj)\n event = obj.event;\n end\n \n function type = getConstraintType(obj)\n type = 'Bank Angle';\n end\n \n% function name = getName(obj)\n% name = sprintf('%s - Event %i', obj.getConstraintType(), obj.event.getEventNum());\n% end\n \n function [unit, lbLim, ubLim, usesLbUb, usesCelBody, usesRefSc] = getConstraintStaticDetails(obj)\n unit = 'deg';\n lbLim = -360;\n ubLim = 360;\n usesLbUb = true;\n usesCelBody = false;\n usesRefSc = false;\n end\n \n function addConstraintTf = openEditConstraintUI(obj, lvdData)\n% addConstraintTf = lvd_EditGenericMAConstraintGUI(obj, lvdData);\n \n output = AppDesignerGUIOutput({false});\n lvd_EditGenericMAConstraintGUI_App(obj, lvdData, output);\n addConstraintTf = output.output{1}; \n end\n end\n \n methods(Static)\n function constraint = getDefaultConstraint(~, ~) \n constraint = BankAngleConstraint(LaunchVehicleEvent.empty(1,0),0,0);\n end\n end\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/ksptot_lvd/classes/Optimization/constraints/@BankAngleConstraint/BankAngleConstraint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.39635603293497074}}
{"text": "function [V,openVariables] = branchVolume(p,openVariables)\n\nif nargin == 1\n d = p.ub(p.branch_variables)-p.lb(p.branch_variables);\n openVariables = find(d~=0);\n d = d(openVariables);\n if any(d<0)\n % This is infeasible!\n V = 0;\n else\n V = geomean(d);\n end\nelse\n if ~p.feasible\n V = 0;\n else\n d = p.ub(p.branch_variables)-p.lb(p.branch_variables);\n d = d(openVariables); \n if any(d<0)\n % This has been propagated to infeasibility\n V = 0;\n else\n V = geomean(d);\n end\n end \nend", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/YALMIP/modules/global/branchVolume.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3963560269375908}}
{"text": "% -*- INTERNAL UNDOCUMENTED FUNCTION -*-\nfunction [geometry, msh, space, sp_mul, eigv, eigf, gnum, dofs_ornt, gnum_mul] = ...\n mp_solve_maxwell_eig_mixed1_3d (problem_data, method_data)\n\nwarning ('geopdes:obsolete','Function MP_SOLVE_MAXWELL_EIG_MIXED1_3D is obsolete. Using MP_SOLVE_MAXWELL_EIG_MIXED1 instead')\n\n[geometry, msh, space, sp_mul, eigv, eigf, gnum, dofs_ornt, gnum_mul] = mp_solve_maxwell_eig_mixed1 (problem_data, method_data);\n\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/obsolete/mp_solve_maxwell_eig_mixed1_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3963560269375908}}
{"text": "% run_simExampleBasisSet.m\n% Jamie Near, McGill University 2014.\n% \n% USAGE:\n% This script is run simply by editing the input parameters and then\n% clicking \"Run\".\n% \n% DESCRIPTION:\n% Script to generate simulated basis spectra for all metabolites of interest\n% in the human brain. The script will generate an LCModel format .RAW file \n% for each metabolite basis spectrum, which can then be passed into \n% LCModel's \"makebasis\" function to generate a complete LCModel basis set.\n% \n% INPUTS:\n% To run this script, edit the following parameters as desired and then click\n% run:\n% lb = linewidth (Hz)\n% np = Spectral points\n% sw = Spectral width (Hz)\n% Bo = Magnetic Field Strength (Tesla)\n% te1 = First PRESS echo time, or SPECIAL echo time (ms)\n% te2 = Second PRESS echo time (if applicable) (ms).\n% seq = Pulse sequence ('se'= SPECIAL, 'p'=press, 'st'=steam);\n% ref = Add reference peak at 0ppm (used in LCModel, y or n);\n%\n% OUTPUTS:\n% H2O = Simulated water spectrum\n% Ala = Simulated alanine spectrum\n% Asp = Simulated aspartate spectrum\n% PCh = Simulated phosphocholine spectrum\n% Cr = Simulated creatine spectrum\n% PCr = Simulated phosphochreatine spectrum\n% GABA = Simulated GABA spectrum\n% Gln = Simulated glutamine spectrum\n% Glu = Simulated glutamate spectrum\n% GSH = Simulated glutathione spectrum\n% Gly = Simulated glycine spectrum\n% Ins = Simulated myo-inositol spectrum\n% Lac = Simulated Lactate spectrum\n% NAA = Simulated NAA spectrum\n% Scyllo = Simulated scyllo-inositol spectrum\n% Tau = Simulated taurine spectrum\n% Asc = Simulated ascorbate spectrum\n% bHB = Simulated beta-hydroxybutyrate spectrum\n% bHG = Simulated 2-hydroxyglutyrate spectrum\n% Glc = Simulated glucose spectrum\n% NAAG = Simulated N-acetylaspartylglutamate spectrum\n% GPC = Simulated glycerophosphocholine spectrum\n% PE = Simulated phosphoethanolamine spectrum\n% Ser = Simulated serine spectrum\n% EtOH = Simulated ethanol spectrum\n%\n% \n% ************INPUT PARAMETERS**********************************\n lb=2; %linewidth (Hz)\n np=8192; %Spectral points\n sw=4000; %Spectral width (Hz)\n Bo=7; %Magnetic Field Strength (Tesla)\n te1=10; %First PRESS echo time, or SPECIAL echo time (ms)\n te2=125; %Second PRESS echo time (if applicable) (ms).\n seq='p' %Pulse sequence ('se'= SPECIAL, 'p'=press, 'st'=steam, 'l'=laser);\n ref='n' %Add reference peak at 0ppm (used in LCModel, y or n);\n% *************END OF INPUT PARAMETERS**************************\n\n [RF,H2O]=sim_lcmrawbasis(np,sw,Bo,lb,'H2O',te1,te2,ref,'y',seq);\n [RF,Ala]=sim_lcmrawbasis(np,sw,Bo,lb,'Ala',te1,te2,ref,'y',seq);\n [RF,Asp]=sim_lcmrawbasis(np,sw,Bo,lb,'Asp',te1,te2,ref,'y',seq);\n [RF,PCh]=sim_lcmrawbasis(np,sw,Bo,lb,'PCh',te1,te2,ref,'y',seq);\n [RF,Cr]=sim_lcmrawbasis(np,sw,Bo,lb,'Cr',te1,te2,ref,'y',seq);\n [RF,PCr]=sim_lcmrawbasis(np,sw,Bo,lb,'PCr',te1,te2,ref,'y',seq);\n [RF,GABA]=sim_lcmrawbasis(np,sw,Bo,lb,'GABA',te1,te2,ref,'y',seq);\n [RF,Gln]=sim_lcmrawbasis(np,sw,Bo,lb,'Gln',te1,te2,ref,'y',seq);\n [RF,Glu]=sim_lcmrawbasis(np,sw,Bo,lb,'Glu',te1,te2,ref,'y',seq);\n [RF,GSH]=sim_lcmrawbasis(np,sw,Bo,lb,'GSH',te1,te2,ref,'y',seq);\n [RF,Gly]=sim_lcmrawbasis(np,sw,Bo,lb,'Gly',te1,te2,ref,'y',seq);\n [RF,Ins]=sim_lcmrawbasis(np,sw,Bo,lb,'Ins',te1,te2,ref,'y',seq);\n [RF,Lac]=sim_lcmrawbasis(np,sw,Bo,lb,'Lac',te1,te2,ref,'y',seq);\n [RF,NAA]=sim_lcmrawbasis(np,sw,Bo,lb,'NAA',te1,te2,ref,'y',seq);\n [RF,Scyllo]=sim_lcmrawbasis(np,sw,Bo,lb,'Scyllo',te1,te2,ref,'y',seq);\n [RF,Tau]=sim_lcmrawbasis(np,sw,Bo,lb,'Tau',te1,te2,ref,'y',seq);\n [RF,Asc]=sim_lcmrawbasis(np,sw,Bo,lb,'Asc',te1,te2,ref,'y',seq);\n [RF,bHB]=sim_lcmrawbasis(np,sw,Bo,lb,'bHB',te1,te2,ref,'y',seq);\n [RF,bHG]=sim_lcmrawbasis(np,sw,Bo,lb,'bHG',te1,te2,ref,'y',seq);\n [RF,Glc]=sim_lcmrawbasis(np,sw,Bo,lb,'Glc',te1,te2,ref,'y',seq);\n [RF,NAAG]=sim_lcmrawbasis(np,sw,Bo,lb,'NAAG',te1,te2,ref,'y',seq);\n [RF,GPC]=sim_lcmrawbasis(np,sw,Bo,lb,'GPC',te1,te2,ref,'y',seq);\n [RF,PE]=sim_lcmrawbasis(np,sw,Bo,lb,'PE',te1,te2,ref,'y',seq);\n [RF,Ser]=sim_lcmrawbasis(np,sw,Bo,lb,'Ser',te1,te2,ref,'y',seq);\n [RF,EtOH]=sim_lcmrawbasis(np,sw,Bo,lb,'EtOH',te1,te2,ref,'y',seq);\n \n\n%LEGEND:\n% 'Ala' = Alanine\n% 'Asp' = Aspartate\n% 'PCh' = PhosphoCholine\n% 'Cr' = Creatine\n% 'PCr' = PhosphoCreatine\n% 'GABA' = Gamma-aminobutyric acid\n% 'Gln' = Glutamine\n% 'Glu' = Glutamate\n% 'GSH' = Glutathione\n% 'Gly' = Glycine\n% 'Ins' = Myo-inositol\n% 'Lac' = Lactate\n% 'NAA' = N-acetyl aspartate\n% 'Scyllo' = Scyllo-inositol\n% 'Tau' = Taurine\n% 'Asc' = Ascorbate (Vitamin C)\n% 'bHB' = beta-Hydroxybutyrate\n% 'bHG' = beta-Hydroxyglutarate\n% 'Glc' = Glucose\n% 'NAAG' = N-acetyl aspartyl glutamate\n% 'GPC' = Glycero-phosphocholine\n% 'PE' = Phosphoryl ethanolamine\n% 'Ser' = Serine\n% 'EtOH' = Ethanol\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/exampleRunScripts/run_simExampleBasisSet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.39635602693759076}}
{"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 tc = tc_visualizeGlm_sparklines(tc);\n%\n% tc = tc_visualizeGlm_sparklines(tc);\n%\n% Visualize results of a general linear model on a time\n% course, using the sparkline method. (See Edward Tufte,\n% \"Beautiful Evidence\".)\n%\n% This is a test to see whether this would work.\n%\n% ras. 01/2007.\nif notDefined('tc')\n tc = get(gcf, 'UserData');\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% apply a GLM if needed\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif ~isfield(tc, 'glm')\n tc = tc_applyGlm(tc);\nend\nX = tc.glm.designMatrix;\nY = tc.wholeTc(:);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% clean up existing objects in figure\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\notherAxes = findobj('Type', 'axes','Parent', tc.ui.fig);\ndelete(otherAxes);\notherUiControls = findobj('Type', 'uicontrol', 'Parent', tc.ui.fig);\ndelete(otherUiControls);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% params\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nnConds = sum(tc.trials.condNums>0);\nnRows = nConds + 1;\nrowSize = min(.15, 1/(nRows+1)); % normalized height of rows\nt = [1:length(tc.wholeTc)] .* tc.TR; % time poitns for wholeTc\n\nlo = min(tc.wholeTc); % min and max time series values\nhi = max(tc.wholeTc); \n\nif isnumeric(tc.params.glmHRF)\n opts = {sprintf('Mean trial for conditions \\n %s',num2str(tc.params.snrConds)), ...\n 'Boynton gamma function', 'SPM difference-of-gammas' ...\n 'Dale & Buckner ''97'};\n hrfName = opts{tc.params.glmHRF};\nelse\n hrfName = tc.params.glmHRF; hrfName(hrfName=='_') = ' ';\nend\ntitle({'HRF function used: ' hrfName}, 'FontWeight', 'bold')\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% plot the data\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfor row = 1:nRows\n subplot('Position', [.3 1-row*rowSize .65 rowSize]);\n \n if row==1 % plot time series data\n plot(t, tc.wholeTc, 'k'); \n else % plot predictor\n plot(t, tc.glm.designMatrix(:,row-1) .* tc.glm.betas(:,row-1), ...\n 'Color', tc.trials.condColors{row});\n end\n axis([t(1) t(end) lo hi]); \n axis off\n \n % label condition\n if row==1\n text(-5, [lo + .3*(hi-lo)], 'Data');\n else\n text(-5, [lo + .3*(hi-lo)], tc.trials.condNames{row});\n end\nend\n\n\n\nreturn\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/EventRelated/TimeCourseUI/tc_visualizeGlm_sparklines.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3963142352254938}}
{"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": "% sbplot() - create axes in arbitrary subplot grid positions and sizes\n%\n% Usage: >> axis_handle = sbplot(v,h,index) \n% >> axis_handle = sbplot(v,h,[index1 index2])\n% >> axis_handle = sbplot(v,h,[index1 index2],axprop,..)\n% >> axis_handle = sbplot(v,h,[index1 index2],'ax',handle,axprop,..)\n%\n% Inputs:\n% v,h - Integers giving the vertical and horizontal ranks of the tiling.\n% index - Either a single subplot index, in which case the command \n% is equivalent to subplot, or a two-element vector giving \n% the indices of two corners of the sbplot() area according \n% to subplot() convention (e.g., left-to-right, top-to-bottom).\n% axprop - Any axes property(s), e.g., >> sbplot(3,3,3,'color','w')\n% handle - Following keyword 'ax', sbplot tiles the given axes handle\n% instead of the whole figure\n%\n% Output:\n% axis_handle - matlab axis handle\n%\n% Note:\n% sbplot is essentially the same as the subplot command except that \n% sbplot axes may span multiple tiles. Also, sbplot() will not erase \n% underlying axes. \n% \n% Examples: >> sbplot(3,3,6);plot(rand(1,10),'g');\n% >> sbplot(3,3,[7 2]);plot(rand(1,10),'r');\n% >> sbplot(8,7,47);plot(rand(1,10),'b'); \n%\n% Authors: Colin Humphries, Arnaud Delorme & Scott Makeig, SCCN/INC/UCSD, La Jolla, June, 1998 \n\n% Copyright (C) June 1998, Colin Humphries & Scott Makeig, SCCN/INC/UCSD, \n% scott@sccn.ucsd.edu\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 Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n% reformatted by Scott Makeig, 6/10/98\n% 12/22/00 test nargin<3 -sm\n% 01/21/01 added (recursive) axes option 'ax' -sm\n% 01-25-02 reformated help & licence -ad \n\nfunction [out] = sbplot(m,n,gridpos,varargin) % varargin is std. matlab arg list\n\nif nargin<3\n error(' requires >=3 arguments');\nend\n\nif nargin>3 & strcmp(varargin{1},'ax')\n pos = get(varargin{2},'Position'); % sbplot(3,1,[2 3]) -> 0.4111 0.1100 0.4939 0.815\n varargin = {varargin{3:end}};\nelse\n pos = get(gcf,'DefaultAxesPosition'); % [0.1300 0.1100 0.7750 0.815]\nend\n\nXpad = pos(1); % lower-left distance from left side of figure\nYpad = pos(2); % lower-left distance from bottom of figure\n\nXlen = pos(3); % axes width\nYlen = pos(4); % axes height\n\nif n == 2\n xspace = Xlen*0.27/(n-0.27); % xspace between axes as per subplot\nelse\n xspace = (0.9*Xlen)*0.27/(n-0.9*0.27); \nend\n\nif m == 2\n yspace = Ylen*0.27/(m-0.27); % yspace between axes as per subplot\nelse % WHY Xlen (.775) instead of Ylen (.815) ??\n yspace = (0.9*Ylen)*0.27/(m-0.9*0.27); \nend\n \nxlength = (Xlen-xspace*(n-1))/n; % axes width\nylength = (Ylen-yspace*(m-1))/m; % axes height\n\n% Convert tile indices to grid positions\nif length(gridpos) == 1\n xgridpos(1) = mod(gridpos,n); % grid position\n if xgridpos(1) == 0\n xgridpos(1) = n; \n end\n xgridpos(2) = 1; % grid length\n ygridpos(1) = m-ceil(gridpos/n)+1; % grid position\n ygridpos(2) = 1; % grid length\nelse\n xgridpos(1) = mod(gridpos(1),n);\n if xgridpos(1) == 0\n xgridpos(1) = n;\n end\n tmp = mod(gridpos(2),n);\n if tmp == 0\n tmp = n;\n end\n if tmp > xgridpos(1)\n xgridpos(2) = tmp-xgridpos(1)+1;\n else\n xgridpos(2) = xgridpos(1)-tmp+1;\n xgridpos(1) = tmp;\n end\n \n ygridpos(1) = m-ceil(gridpos(1)/n)+1;\n tmp = m-ceil(gridpos(2)/n)+1;\n if tmp > ygridpos(1)\n ygridpos(2) = tmp-ygridpos(1)+1;\n else \n ygridpos(2) = ygridpos(1)-tmp+1;\n ygridpos(1) = tmp;\n end\nend\n\n% Calculate axes coordinates\nposition(1) = Xpad+xspace*(xgridpos(1)-1)+xlength*(xgridpos(1)-1);\nposition(2) = Ypad+yspace*(ygridpos(1)-1)+ylength*(ygridpos(1)-1)-0.03;\nposition(3) = xspace*(xgridpos(2)-1)+xlength*xgridpos(2);\nposition(4) = yspace*(ygridpos(2)-1)+ylength*ygridpos(2);\n\n% Create new axes\nax = axes('Position',position,varargin{:});\n\n% Output axes handle\nif nargout > 0\n out = ax; \nend\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/functions/sigprocfunc/sbplot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.39625504762123004}}
{"text": "function varargout = xyz2lab(varargin)\n% VL_XYZ2LAB Convert XYZ color space to LAB\n% J = VL_XYZ2LAB(I) converts the image from XYZ format to LAB format.\n%\n% VL_XYZ2LAB(I,IL) uses one of the illuminants A, B, C, E, D50, D55,\n% D65, D75, D93. The default illuminatn is E.\n%\n% See also: VL_XYZ2LUV(), VL_HELP().\n[varargout{1:nargout}] = vl_xyz2lab(varargin{:});\n", "meta": {"author": "yihui-he", "repo": "panorama", "sha": "0c993d4ba6780dcb175b2c1fc7d25b513b7bb39b", "save_path": "github-repos/MATLAB/yihui-he-panorama", "path": "github-repos/MATLAB/yihui-he-panorama/panorama-0c993d4ba6780dcb175b2c1fc7d25b513b7bb39b/lib/vlfeat-0.9.20/toolbox/noprefix/xyz2lab.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6150878555160666, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.39625503921831073}}
{"text": "function image=sr_bw(t2,handle_wb,offset_wb,scale_wb,ds,max_shift,th_prob1,th_prob2,no_iter)\n\nif ~exist('ds','var')\n ds=4; % four time super resolution\nend\nif ~exist('max_shift','var')\n max_shift=8;\nend\nif ~exist('th_prob1','var')\n th_prob1=0.9;\nend\nif ~exist('th_prob2','var')\n th_prob2=0.85;\nend\nif ~exist('no_iter','var')\n no_iter=2;\nend\n\nfprintf('start SR\\n...');\nsearch_range=[-max_shift max_shift -max_shift max_shift]; \nimage=kron(t2{1},ones(ds));\n\nsigma=-1; % use the default sigma to estimate prob (see also subpixel_register.m)\nfprintf('start super-resolution 1st phase...\\n');\ntic\n[image,probs,shs,scores]=sr_one_step_wb(image,t2,'average',ds,search_range,sigma,th_prob1,handle_wb,offset_wb,scale_wb/2); %,...\ntoc\n\nfprintf('start super-resolution 2nd phase...\\n');\nfor iter=1:no_iter\n tic\n [image,probs,shs,scores]=sr_one_step_wb(image,t2,'sort_pocs',ds,search_range,sigma,th_prob2,handle_wb,offset_wb+(iter-1)*scale_wb/2/no_iter+scale_wb/2,scale_wb/2/no_iter);\n toc\n iter\n if length(find(probs>th_prob2))==length(probs)\n break;\n end\nend\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/30488-superresolution-demo/sr_demo/sr_bw.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.3961326310189647}}
{"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 [g]= spm_gx_adem_write(x,v,a,P)\n% returns the prediction for a two-joint arm (proprioception and vision)\n% FORMAT [g]= spm_gx_adem_write(x,v,a,P)\n%\n% x - hidden states:\n% x(1) - joint angle\n% x(2) - joint angle\n% x(3) - angular velocity\n% x(4) - angular velocity\n% v - causal states{\n% v(1) - exogenous force (x)\n% v(2) - exogenous force (y)\n% a - action\n% P - parameters\n%\n% g - sensations:\n% g(1) - joint angle (proprioception)\n% g(2) - joint angle (proprioception)\n% g(3) - arm location (visual)\n% g(4) - arm location (visual)\n% \n% As for spm_dem_reach but with no visual target\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n \n% Karl Friston\n% $Id: spm_gx_adem_write.m 3901 2010-05-27 16:14:36Z karl $\n\n% evaluate positions\n%--------------------------------------------------------------------------\nJ = spm_dem_reach_x2J(x);\n\n% stretch (angular) and visual (positional) information about motor plant\n%==========================================================================\ng = [x; J{1}; J{1} + J{2}];\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_gx_adem_write.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825007, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.39608965399668133}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Demonstration of Basic Utilities of JSONlab\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nrngstate = rand ('state');\nrandseed=hex2dec('623F9A9E');\nclear data2json json2data\n\nfprintf(1,'\\n%%=================================================\\n')\nfprintf(1,'%% a simple scalar value \\n')\nfprintf(1,'%%=================================================\\n\\n')\n\ndata2json=pi\nsavebj('',data2json)\njson2data=loadbj(ans)\n\nfprintf(1,'\\n%%=================================================\\n')\nfprintf(1,'%% an empty array \\n')\nfprintf(1,'%%=================================================\\n\\n')\n\ndata2json=[]\nsavebj('empty',data2json)\njson2data=loadbj(ans)\n\nfprintf(1,'\\n%%=================================================\\n')\nfprintf(1,'%% an ampty string \\n')\nfprintf(1,'%%=================================================\\n\\n')\n\ndata2json=''\nsavebj('emptystr',data2json)\njson2data=loadbj(ans)\n\nfprintf(1,'\\n%%=================================================\\n')\nfprintf(1,'%% a simple row vector \\n')\nfprintf(1,'%%=================================================\\n\\n')\n\ndata2json=1:3\nsavebj('',data2json)\njson2data=loadbj(ans)\n\nfprintf(1,'\\n%%=================================================\\n')\nfprintf(1,'%% a simple column vector \\n')\nfprintf(1,'%%=================================================\\n\\n')\n\ndata2json=(1:3)'\nsavebj('',data2json)\njson2data=loadbj(ans)\n\nfprintf(1,'\\n%%=================================================\\n')\nfprintf(1,'%% a string array \\n')\nfprintf(1,'%%=================================================\\n\\n')\n\ndata2json=['AC';'EG']\nsavebj('',data2json)\njson2data=loadbj(ans)\n\nfprintf(1,'\\n%%=================================================\\n')\nfprintf(1,'%% a string with escape symbols \\n')\nfprintf(1,'%%=================================================\\n\\n')\n\ndata2json=sprintf('AB\\tCD\\none\"two')\nsavebj('str',data2json)\njson2data=loadbj(ans)\n\nfprintf(1,'\\n%%=================================================\\n')\nfprintf(1,'%% a mix-typed cell \\n')\nfprintf(1,'%%=================================================\\n\\n')\n\ndata2json={'a',true,[2;3]}\nsavebj('',data2json)\njson2data=loadbj(ans)\n\nfprintf(1,'\\n%%=================================================\\n')\nfprintf(1,'%% a 3-D array in nested array form\\n')\nfprintf(1,'%%=================================================\\n\\n')\n\ndata2json=reshape(1:(2*4*6),[2,4,6]);\nsavebj('',data2json,'NestArray',1)\njson2data=loadbj(ans)\n% if(any(json2data(:)~=data2json(:)) || any(size(json2data)~=size(data2json)))\n% warning('conversion does not preserve original data');\n% end\n\nfprintf(1,'\\n%%=================================================\\n')\nfprintf(1,'%% a 3-D array in annotated array form\\n')\nfprintf(1,'%%=================================================\\n\\n')\n\ndata2json=reshape(1:(2*4*6),[2,4,6]);\nsavebj('',data2json,'NestArray',0)\njson2data=loadbj(ans)\nif(any(json2data(:)~=data2json(:)) || any(size(json2data)~=size(data2json)))\n warning('conversion does not preserve original data');\nend\n\nfprintf(1,'\\n%%=================================================\\n')\nfprintf(1,'%% a 4-D array in annotated array form\\n')\nfprintf(1,'%%=================================================\\n\\n')\n\ndata2json=reshape(1:(2*4*3*2),[2,4,3,2]);\nsavebj('',data2json,'NestArray',0) % nestarray for 4-D or above is not working\njson2data=loadbj(ans)\nif(any(json2data(:)~=data2json(:)) || any(size(json2data)~=size(data2json)))\n warning('conversion does not preserve original data');\nend\n\nfprintf(1,'\\n%%=================================================\\n')\nfprintf(1,'%% a 3-D array in nested array form (JSONLab 1.9)\\n')\nfprintf(1,'%%=================================================\\n\\n')\n\ndata2json=reshape(1:(2*4*6),[2,4,6]);\nsavebj('',data2json,'NestArray',1,'FormatVersion',1.8)\n\nfprintf(1,'\\n%%=================================================\\n')\nfprintf(1,'%% a 3-D array in annotated array form (JSONLab 1.9 or earlier)\\n')\nfprintf(1,'%%=================================================\\n\\n')\n\ndata2json=reshape(1:(2*4*6),[2,4,6]);\nsavebj('',data2json,'NestArray',0,'FormatVersion',1.8)\n\nfprintf(1,'\\n%%=================================================\\n')\nfprintf(1,'%% a complex number\\n')\nfprintf(1,'%%=================================================\\n\\n')\n\ndata2json=1+2i\nsavebj('',data2json)\njson2data=loadbj(ans) \n\nfprintf(1,'\\n%%=================================================\\n')\nfprintf(1,'%% a complex matrix\\n')\nfprintf(1,'%%=================================================\\n\\n')\n\ndata2json=magic(6);\ndata2json=data2json(:,1:3)+data2json(:,4:6)*1i\nsavebj('',data2json)\njson2data=loadbj(ans)\n\nfprintf(1,'\\n%%=================================================\\n')\nfprintf(1,'%% MATLAB special constants\\n')\nfprintf(1,'%%=================================================\\n\\n')\n\ndata2json=[NaN Inf -Inf]\nsavebj('specials',data2json)\njson2data=loadbj(ans)\n\nfprintf(1,'\\n%%=================================================\\n')\nfprintf(1,'%% a real sparse matrix\\n')\nfprintf(1,'%%=================================================\\n\\n')\n\ndata2json=sprand(10,10,0.1)\nsavebj('sparse',data2json)\njson2data=loadbj(ans)\n\nfprintf(1,'\\n%%=================================================\\n')\nfprintf(1,'%% a complex sparse matrix\\n')\nfprintf(1,'%%=================================================\\n\\n')\n\ndata2json=data2json-data2json*1i\nsavebj('complex_sparse',data2json)\njson2data=loadbj(ans)\n\nfprintf(1,'\\n%%=================================================\\n')\nfprintf(1,'%% an all-zero sparse matrix\\n')\nfprintf(1,'%%=================================================\\n\\n')\n\ndata2json=sparse(2,3);\nsavebj('all_zero_sparse',data2json)\njson2data=loadbj(ans)\n\nfprintf(1,'\\n%%=================================================\\n')\nfprintf(1,'%% an empty sparse matrix\\n')\nfprintf(1,'%%=================================================\\n\\n')\n\ndata2json=sparse([]);\nsavebj('empty_sparse',data2json)\njson2data=loadbj(ans)\n\nfprintf(1,'\\n%%=================================================\\n')\nfprintf(1,'%% an empty 0-by-0 real matrix\\n')\nfprintf(1,'%%=================================================\\n\\n')\n\ndata2json=[];\nsavebj('empty_0by0_real',data2json)\njson2data=loadbj(ans)\n\nfprintf(1,'\\n%%=================================================\\n')\nfprintf(1,'%% an empty 0-by-3 real matrix\\n')\nfprintf(1,'%%=================================================\\n\\n')\n\ndata2json=zeros(0,3);\nsavebj('empty_0by3_real',data2json)\njson2data=loadbj(ans)\n\nfprintf(1,'\\n%%=================================================\\n')\nfprintf(1,'%% a sparse real column vector\\n')\nfprintf(1,'%%=================================================\\n\\n')\n\ndata2json=sparse([0,3,0,1,4]');\nsavebj('sparse_column_vector',data2json)\njson2data=loadbj(ans)\n\nfprintf(1,'\\n%%=================================================\\n')\nfprintf(1,'%% a sparse complex column vector\\n')\nfprintf(1,'%%=================================================\\n\\n')\n\ndata2json=data2json-1i*data2json;\nsavebj('complex_sparse_column_vector',data2json)\njson2data=loadbj(ans)\n\nfprintf(1,'\\n%%=================================================\\n')\nfprintf(1,'%% a sparse real row vector\\n')\nfprintf(1,'%%=================================================\\n\\n')\n\ndata2json=sparse([0,3,0,1,4]);\nsavebj('sparse_row_vector',data2json)\njson2data=loadbj(ans)\n\nfprintf(1,'\\n%%=================================================\\n')\nfprintf(1,'%% a sparse complex row vector\\n')\nfprintf(1,'%%=================================================\\n\\n')\n\ndata2json=data2json-1i*data2json;\nsavebj('complex_sparse_row_vector',data2json)\njson2data=loadbj(ans)\n\nfprintf(1,'\\n%%=================================================\\n')\nfprintf(1,'%% a structure\\n')\nfprintf(1,'%%=================================================\\n\\n')\n\ndata2json=struct('name','Think Different','year',1997,'magic',magic(3),...\n 'misfits',[Inf,NaN],'embedded',struct('left',true,'right',false))\nsavebj('astruct',data2json,struct('ParseLogical',1))\njson2data=loadbj(ans)\nclass(json2data.astruct.embedded.left)\n\nfprintf(1,'\\n%%=================================================\\n')\nfprintf(1,'%% a structure array\\n')\nfprintf(1,'%%=================================================\\n\\n')\n\ndata2json=struct('name','Nexus Prime','rank',9);\ndata2json(2)=struct('name','Sentinel Prime','rank',9);\ndata2json(3)=struct('name','Optimus Prime','rank',9);\nsavebj('Supreme Commander',data2json)\njson2data=loadbj(ans)\n\nfprintf(1,'\\n%%=================================================\\n')\nfprintf(1,'%% a cell array\\n')\nfprintf(1,'%%=================================================\\n\\n')\n\ndata2json=cell(3,1);\ndata2json{1}=struct('buzz',1.1,'rex',1.2,'bo',1.3,'hamm',2.0,'slink',2.1,'potato',2.2,...\n 'woody',3.0,'sarge',3.1,'etch',4.0,'lenny',5.0,'squeeze',6.0,'wheezy',7.0);\ndata2json{2}=struct('Ubuntu',['Kubuntu';'Xubuntu';'Lubuntu']);\ndata2json{3}=[10.04,10.10,11.04,11.10]\nsavebj('debian',data2json,struct('FloatFormat','%.2f'))\njson2data=loadbj(ans)\n\nfprintf(1,'\\n%%=================================================\\n')\nfprintf(1,'%% invalid field-name handling\\n')\nfprintf(1,'%%=================================================\\n\\n')\n\njson2data=loadbj(savebj('',loadjson('{\"ValidName\":1, \"_InvalidName\":2, \":Field:\":3, \"\u9879\u76ee\":\"\u7edd\u5bc6\"}')))\n\nfprintf(1,'\\n%%=================================================\\n')\nfprintf(1,'%% a function handle\\n')\nfprintf(1,'%%=================================================\\n\\n')\n\ndata2json=@(x) x+1\nsavebj('handle',data2json)\njson2data=loadbj(ans)\n\nfprintf(1,'\\n%%=================================================\\n')\nfprintf(1,'%% a 2D cell array\\n')\nfprintf(1,'%%=================================================\\n\\n')\n\ndata2json={{1,{2,3}},{4,5},{6};{7},{8,9},{10}};\nsavebj('data2json',data2json)\njson2data=loadbj(ans) % only savebj works for cell arrays, loadbj has issues\n\nfprintf(1,'\\n%%=================================================\\n')\nfprintf(1,'%% a 2D struct array\\n')\nfprintf(1,'%%=================================================\\n\\n')\n\ndata2json=repmat(struct('idx',0,'data','structs'),[2,3])\nfor i=1:6\n data2json(i).idx=i;\nend\nsavebj('data2json',data2json)\njson2data=loadbj(ans)\n\n\nif(exist('datetime'))\n fprintf(1,'\\n%%=================================================\\n')\n fprintf(1,'%% datetime object \\n')\n fprintf(1,'%%=================================================\\n\\n')\n\n data2json=datetime({'8 April 2015','9 May 2015'}, 'InputFormat','d MMMM yyyy')\n savebj('',data2json)\n json2data=loadbj(ans)\nend\n\nif(exist('containers.Map'))\n fprintf(1,'\\n%%=================================================\\n')\n fprintf(1,'%% a container.Maps object \\n')\n fprintf(1,'%%=================================================\\n\\n')\n\n data2json=containers.Map({'Andy','William','Om'},{21,21,22})\n savebj('',data2json)\n json2data=loadbj(ans)\nend\n\nif(exist('istable'))\n fprintf(1,'\\n%%=================================================\\n')\n fprintf(1,'%% a table object \\n')\n fprintf(1,'%%=================================================\\n\\n')\n\n Names={'Andy','William','Om'}';\n Age=[21,21,22]';\n data2json=table(Names,Age)\n savebj('table',table(Names,Age))\n json2data=loadbj(ans)\nend\n\nif(exist('bandwidth'))\n fprintf(1,'\\n%%=================================================\\n')\n fprintf(1,'%% use _ArrayShape_ \\n')\n fprintf(1,'%%=================================================\\n\\n')\n\n lband=2;\n uband=3;\n data2json=spdiags(true(8,lband+uband+1),-uband:lband,5,8);\n data2json=full(double(data2json));\n data2json(data2json~=0)=find(data2json)\n\n savebj('',data2json,'usearrayshape',1)\n json2data=loadbj(ans,'fullarrayshape',1)\n \n savebj('',tril(data2json),'usearrayshape',1)\n json2data=loadbj(ans,'fullarrayshape',1)\n \n savebj('',triu(data2json+1i*data2json),'usearrayshape',1)\n json2data=loadbj(ans,'fullarrayshape',1)\n \n savebj('',tril(triu(int8(data2json))),'usearrayshape',1)\n json2data=loadbj(ans,'fullarrayshape',1)\n \n savebj('',data2json(:,1:5)+data2json(:,1:5)','usearrayshape',1)\n json2data=loadbj(ans,'fullarrayshape',1)\nend\n\ntry\n val=zlibencode('test');\n fprintf(1,'\\n%%=================================================\\n')\n fprintf(1,'%% a 2-D array in compressed array format\\n')\n fprintf(1,'%%=================================================\\n\\n')\n\n data2json=eye(10);\n data2json(20,1)=1;\n savebj('',data2json,'Compression','zlib','CompressArraySize',0) % nestarray for 4-D or above is not working\n json2data=loadbj(ans)\n if(any(json2data(:)~=data2json(:)) || any(size(json2data)~=size(data2json)))\n warning('conversion does not preserve original data');\n end\ncatch\nend\n\nrand ('state',rngstate);\n\n", "meta": {"author": "fangq", "repo": "jsonlab", "sha": "cb43ed1655021f8d08844ce3a3613916abc62e2d", "save_path": "github-repos/MATLAB/fangq-jsonlab", "path": "github-repos/MATLAB/fangq-jsonlab/jsonlab-cb43ed1655021f8d08844ce3a3613916abc62e2d/examples/demo_ubjson_basic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.3960661459449894}}
{"text": "function [volume_pix_size] = mrGetVolPixSize(voldr,subject)\n%function [volume_pix_size] = mrGetVolPixSize(voldr,subject)\n%\n% PURPOSE: Prompt the user for the volume pixel size\n% AUTHOR: Poirson \n% DATE: 03.16.98\n% HISTORY: Based on routine by Geoff Boynton \n% NOTES: The default values [256/240,256/240,1/1] mean that\n% 24 cm of brain image are interpolated on the 256 pixels\n% in the x and y dimensions (units are pixels/mm).\n% And that the volume plane thickness is 1 pixel per 1 mm.\n%\n% 09.17.99 RFD: cleaned up the code a bit.\n% 04.01.01 ARW : Shouldn't that default 1mm be a 124/150mm?\n% See if we can just read the values\nif nargin<2 % new way- full path is passed in\n\tparamsFile = [voldr,filesep,'UnfoldParams'];\nelse % old method- pass two variable that must be combined (why?)\n \tparamsFile = [voldr,filesep,subject,filesep,'UnfoldParams'];\nend\n\nif ~exist([paramsFile '.mat'], 'file')\n disp ([paramsFile ' not found.']);\n disp ('Please enter values.');\n disp('Enter size of volume anatomy pixels/mm in x,y and z directions');\n volume_pix_size=input('Default is [256/240,256/240,124/150]: ');\n\n if isempty(volume_pix_size)\n volume_pix_size=[256/240,256/240,124/150];\n end\n\n %Create the file 'UnfoldParams.mat' in the subject's volume anatomy directory\n estr=(['save ' paramsFile ' volume_pix_size']);\n eval(estr);\nelse \t% Load in the infolding parameters (volme_pix_sizes)\n estr=(['load ' paramsFile]);\n eval(estr);\n volume_pix_size = volume_pix_size;\nend\n\nreturn\n\n\n\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrAlign/pixel/mrGetVolPixSize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.39606613803678226}}
{"text": "function dh=constDhDataOf14R820()\n%% This function returns the DH parameters \n% for the KUKA iiwa 7R800\n\n% The dimnstions are taken from Kuka manuals:\n% [1] Medien-Flansch\n% F\u00fcr Produktfamilie LBR iiwa\n% Montage- und Betriebsanleitung\n\n%% DH PARAMETERS FOR THE ROBOT\ndh.alfa={0,-pi/2,pi/2,pi/2,-pi/2,-pi/2,pi/2};\n% following are \"d\" parameters for iiwa 14 R 820 \ndh.d={0.36,0.0,0.42,0.0,0.4,0.0,0.126};\ndh.a={0,0,0,0,0,0,0};\nend", "meta": {"author": "Modi1987", "repo": "KST-Kuka-Sunrise-Toolbox", "sha": "9299bed2b46058aeb4105d7fbff6d2290ce68bba", "save_path": "github-repos/MATLAB/Modi1987-KST-Kuka-Sunrise-Toolbox", "path": "github-repos/MATLAB/Modi1987-KST-Kuka-Sunrise-Toolbox/KST-Kuka-Sunrise-Toolbox-9299bed2b46058aeb4105d7fbff6d2290ce68bba/Matlab_client/constDhDataOf14R820.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.3960661380367822}}
{"text": "function msm_to_mm_test18 ( )\n\n%*****************************************************************************80\n%\n%% MSM_TO_MM_TEST18 tests MSM_TO_MM_COORDINATE_REAL_GENERAL.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 November 2008\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'MSM_TO_MM_TEST18\\n' );\n fprintf ( 1, ' Convert an MSM to MM coordinate real general format.\\n' );\n\n output_filename = 'msm_to_mm_test18.mm';\n\n a = r8mat_indicator ( 5, 3 );\n%\n% Have MSM_TO_MM write the matrix to a file.\n%\n msm_to_mm ( output_filename, a, 'coordinate', 'real', 'general' );\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/msm_to_mm/msm_to_mm_test18.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.7401743620390162, "lm_q1q2_score": 0.3960661380367822}}
{"text": "% This function generate the log Mel filterbanks features of the training\n% and evaluation data. Note that the filterbanks features generated here is\n% slightly different from that by other toolkits, such as Kaldi. \n% This recipe will always use the filterbank features generated in the same\n% way as in this function, so we will be able to do joint training of\n% feature extraction and acoustic modeling later. (e.g. you cannot use\n% Kaldi fbank features in joint training unless you have Matlab version of\n% the Kaldi feature extraction. \n\nfunction GenFbankFeatures(dataset)\naddpath('lib');\n\n% load the wavelist\n\nchime_root = ChoosePath4OS({'D:/Data/CHiME4', '/home/xiaoxiong/CHiME4'}); % you can set two paths, first for windows OS and second for Linux OS. \nfbank_root = [chime_root '/fbank/plain'];\n\nswitch dataset\n case 'tr05_orig'\n wavlist = findFiles([chime_root '/audio/isolated/tr05_org']);\n case 'tr05'\n \n case 'dt05'\n \n case 'et05'\n \n otherwise\n fprintf('Unknown dataset: %s!\\n', dataset);\nend\n\n[layer, para] = BuildFbankExtractionNet();\n\nfor i=1:length(wavlist)\n PrintProgress(i-1, length(wavlist), 100, 'Generate filterbank');\n words = ExtractWordsFromString_v2(wavlist{i}, '/');\n wav = audioread(wavlist{i});\n wav = StoreWavInt16(wav');\n Data(1).data{1} = wav;\n \n [fbank, layer2] = FeatureTree2(Data, para, layer);\n fbank = fbank{1}{1};\n \n fbank_file = [fbank_root '/' words{end-2} '/' words{end-1} '/' words{end}(1:end-4) '.fbank'];\n fbank_dir = fileparts(fbank_file);\n my_mkdir(fbank_dir);\n writeHTK(fbank_file, fbank', 'MFCC_0', 1);\n \nend\n", "meta": {"author": "singaxiong", "repo": "SignalGraph", "sha": "e86d973556ae8796a05ee2adbd665f47c8525a21", "save_path": "github-repos/MATLAB/singaxiong-SignalGraph", "path": "github-repos/MATLAB/singaxiong-SignalGraph/SignalGraph-e86d973556ae8796a05ee2adbd665f47c8525a21/examples/beamforming/GenFbankFeatures.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 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 [vertices, faces] = readMesh_off(fileName)\n%READMESH_OFF Read mesh data stord in OFF format\n%\n% [VERTICES FACES] = readMesh_off(FILNAME)\n%\n% Example\n% [v, f] = readMesh_off('mushroom.off');\n% figure; drawMesh(v, f, 'faceColor', [0 1 0], 'edgeColor', 'none')\n% view([5 80]); light; lighting gouraud\n%\n% See also\n% meshes3d, drawMesh\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2011-12-20, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2011 INRA - Cepia Software Platform.\n\n% open file\nf = fopen(fileName, 'r');\nif f == -1 \n error('matGeom:readMesh_off:FileNotFound', ...\n ['Could not find file: ' fileName]);\nend\n\n% check format\nline = fgets(f); % -1 if eof\nif ~strcmp(line(1:3), 'OFF')\n error('matGeom:readMesh_off:FileFormatError', ...\n 'Not a valid OFF file'); \nend\n\n% number of faces and vertices\nline = fgets(f);\nvals = sscanf(line, '%d %d');\nnv = vals(1);\nnf = vals(2);\n\n\n% read vertex data\n[vertices, count] = fscanf(f, '%f ', [3 nv]);\nif count ~= nv*3\n error('matGeom:readMesh_off:FileFormatError', ...\n ['Could not read all the ' num2str(nv) ' vertices']);\nend\nvertices = vertices';\n\n% read face data (face start by index)\n[faces, count] = fscanf(f, '%d %d %d %d\\n', [4 nf]);\nif count ~= nf * 4\n error('matGeom:readMesh_off:FileFormatError', ...\n ['Could not read all the ' num2str(nf) ' faces']);\nend\n\n% clean up: remove index, and use 1-indexing\nfaces = faces(2:4, :)' + 1;\n\n% close the file\nfclose(f);\n\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/meshes3d/readMesh_off.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6113819874558603, "lm_q2_score": 0.6477982247516796, "lm_q1q2_score": 0.3960521661190599}}
{"text": "function tri2tgf(input_name,output_name)\n % TRI2TGF Script to convert a triangle mesh to a tgf graph (skeleton file)\n %\n % tri2tgf(input_name,output_name)\n %\n % Inputs:\n % input_name name of file contaning input vertices and faces of surface,\n % should end in .off or .obj\n % output_name name of output file to be written with 3D tet mesh, should\n % end in .mesh\n\n % read input mesh\n [V,F] = load_mesh(input_name);\n % Find all edges in mesh, note internal edges are repeated\n E = sort( ...\n [F(:,1) (:,2); ...\n F(:,2) (:,3); ...\n F(:,3) (:,1)]')';\n % remove duplicates\n E = unique(E,'rows');\n writeTGF(output_name,V,E);\n\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/tri2tgf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.3960521527879958}}
{"text": "function res = uminusFactorized( xi )\n%UMINUSFACTORIZED Unary minus for a tangent tensor.\n% RES = UMINUSFACTORIZED( XI ) performs unary minus operation\n% on the tangent tensor XI given in factorized form\n%\n% See also addFactorized\n%\n\n% GeomCG Tensor Completion. Copyright 2013 by\n% Michael Steinlechner\n% Questions and contact: michael.steinlechner@epfl.ch\n% BSD 2-clause license, see LICENSE.txt\n\n res.Y_tilde = -xi.Y_tilde;\n res.U1_tilde = -xi.U1_tilde;\n res.U2_tilde = -xi.U2_tilde;\n res.U3_tilde = -xi.U3_tilde;\nend\n", "meta": {"author": "andrewssobral", "repo": "mctc4bmi", "sha": "fbcbcd25654b818646387c3d6a64304fb60e12dd", "save_path": "github-repos/MATLAB/andrewssobral-mctc4bmi", "path": "github-repos/MATLAB/andrewssobral-mctc4bmi/mctc4bmi-fbcbcd25654b818646387c3d6a64304fb60e12dd/algs_tc/geomCG/uminusFactorized.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6477982043529715, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.3960521444737275}}
{"text": "function obj = SSP_OMP_method(obj)\n\nt1 = clock;\n[F_RF,F_BB] = OMP_Precoding();\n[W_RF,W_BB] = OMP_Combining(F_RF,F_BB);\nF = F_RF * F_BB;\nW = W_RF * W_BB;\n\nt2 = clock;\nruntime = etime(t2,t1);\nobj.runtime = obj.runtime + runtime;\nobj.V_B = F_BB;\nobj.W_B = W_BB;\nobj.V_RF = F_RF;\nobj.W_RF = W_RF;\nobj = get_metric(obj);", "meta": {"author": "Zzhaoxingyu", "repo": "hybrid-beamforming-for-three-scenes", "sha": "396ae70db7dd464a65458f274a65aa113ed73c8b", "save_path": "github-repos/MATLAB/Zzhaoxingyu-hybrid-beamforming-for-three-scenes", "path": "github-repos/MATLAB/Zzhaoxingyu-hybrid-beamforming-for-three-scenes/hybrid-beamforming-for-three-scenes-396ae70db7dd464a65458f274a65aa113ed73c8b/narrowband/Algorithms/SSP_OMP/SSP_OMP_method.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3959755304387104}}
{"text": "% script to specify network arch and train drdae on single machine\n% make copies of this script for each architecture you want to try\n\n%% setup paths for code. assumed this script runs in its own directory\ncodeDir = '/afs/cs.stanford.edu/u/awni/scr/noise_proj/audio_ufl/matlab_wd/drdae';\nminFuncDir = '/afs/cs/u/amaas/scratch/matlab_trunk/parallel_proto/minFunc/';\nbaseDir = '/afs/cs.stanford.edu/u/awni/scr/noise_proj/aurora2/features/';\n%% AMAAS setup\n%codeDir = '/afs/cs.stanford.edu/u/amaas/scratch/audio/audio_repo/matlab_wd/drdae';\n%% add paths\naddpath(codeDir);\naddpath(minFuncDir);\n\n%% setup network architecture\neI = [];\n% dimension of each input frame\neI.featDim = 14;\neI.dropout = 0;\n% context window size of the input.\neI.winSize = 3;\n% weight tying in hidden layers\n% if you want tied weights, must have odd number of *hidden* layers\neI.tieWeights = 0;\n% 2 hidden layers and output layer\neI.layerSizes = [512 eI.featDim];\n% highest hidden layer is temporal\neI.temporalLayer = 0;\n% dim of network input at each timestep (final size after window & whiten)\neI.inputDim = eI.featDim * eI.winSize;\n% length of input sequence chunks.\neI.seqLen = [1 10 25 50 100];\n% activation function\neI.activationFn = 'tanh';\n% temporal initialization type\neI.temporalInit = 'rand';\n% weight norm penaly\neI.lambda = 0;\n% file containing whitening matrices for outputs\neI.targetWhiten = [codeDir '/aurora_whiten.mat'];\n%% setup weight caching\nsaveDir = '/scail/group/deeplearning/speech/awni/aurora_results/';\neI.saveDir = [saveDir 'model_1hl512_ws3_small_test/'];\nmkdir(eI.saveDir);\n%% initialize weights\n[stack_i, W_t_i] = initialize_weights(eI);\n[theta] = rnn_stack2params(stack_i, eI, W_t_i);\n\n[stack_new, W_t_new] = rnn_params2stack(theta,eI);\n[theta_new] = rnn_stack2params(stack_new, eI, W_t_new);\n%% Directory of features\neI.featInBase =baseDir; % '/afs/cs.stanford.edu/u/amaas/scratch/aurora2/features/';\n\n%% load data\neI.useCache = 0;\n\n%Get SNR List\nsnrList = {'clean1', 'N1_SNR5', 'N1_SNR10', 'N1_SNR15', 'N1_SNR20', ...\n'clean2', 'N2_SNR5', 'N2_SNR10', 'N2_SNR15', 'N2_SNR20', ...\n'clean3', 'N3_SNR5', 'N3_SNR10', 'N3_SNR15', 'N3_SNR20', };\neI.subdirs = snrList;\n[data_cell, targets_cell] = load_aurora( baseDir, 'Mfc08_multiTR', snrList, -1, eI );\n\n% dieplay mean as a whitening debug check\n%disp(mean(data_cell{1},2));\n%% setup minFunc\noptions.Diagnostics = 'on';\noptions.Display = 'iter';\noptions.MaxIter = 2000;\noptions.MaxFunEvals = 2500;\noptions.Corr = 50;\noptions.DerivativeCheck = 'off';\noptions.outputFcn = @save_callback;\n%% run optimizer\nminFunc(@drdae_obj, theta, options, eI, data_cell, targets_cell, false, false);\n", "meta": {"author": "amaas", "repo": "rnn-speech-denoising", "sha": "55edd5bc4719f9747e390b9d57240aa5828c55d3", "save_path": "github-repos/MATLAB/amaas-rnn-speech-denoising", "path": "github-repos/MATLAB/amaas-rnn-speech-denoising/rnn-speech-denoising-55edd5bc4719f9747e390b9d57240aa5828c55d3/train_aurora_local.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3959755304387104}}
{"text": "function [sigma q_a out_counts score lv_score word_score] = tamEStepNoMex(x,beta,alpha,a_log_prior,sigma)\n%function [sigma q_a out_counts score lv_score word_score] = tamEStepNoMex(x,beta,alpha,a_log_prior,sigma)\n%\n%this contains a lot of optimizations that make it kind of complicated.\n%maybe i should release a simplified version?\n[W K A] = size(beta);\nif nargin < 5\n if isscalar(alpha), sigma = ones(1,K) * (numel(x) / K + alpha);\n else sigma = ones(1,K) * numel(x) / K + alpha; end\nend\nmydudes = x>0;\nq_a = normalize_vec(ones(1,A));\nmyphi = 1/K * ones(sum(mydudes),K);\nmyx = x(mydudes);\nmybeta = beta(mydudes,:,:);\n\n%new_counts = spalloc(K,W,sum(mydudes)*K);\nxrep = full(repmat(myx',1,K));\niter = newIterator(5,'thresh',1e-4,'debug',false);\n%iter_delta = newDeltaIterator(1000,'thresh',1e-3);\niter_ctr = 0;\nwhile ~iter.done\n sigma = (myx * myphi + alpha);\n dig_sig = digamma(sigma) - digamma(sum(sigma));\n warning off;\n myphi = logToSimplex2(tprod(mybeta,[1 2 -1],q_a,[3 -1],'n') + repmat(dig_sig,size(myx,2),1));\n [q_a log_q_a] = logToSimplex2(squeeze(tprod(mybeta,[-1 -2 1],myphi,[-1 -2],'n'))' + a_log_prior);\n warning on;\n %score it. this is slow, so we do it less often.\n if rem(iter_ctr,5) == 0\n word_score = 0;\n %new_counts(:,mydudes) = transpose(myphi.*xrep);\n my_new_counts = transpose(myphi.*xrep);\n %for a = 1:A\n %new_counts = new_counts * q_a(a);\n % word_score = word_score + q_a(a) * scoreWords(my_new_counts',mybeta(:,:,a));\n %end\n %same as above, but faster\n word_score = q_a * tprod(my_new_counts,[-1 -2],mybeta,[-2 -1 1],'n');\n %using mybeta(:,:,1) looks weird, but actually this part is being ignored, we're only using the latent variable score. so this is legit.\n [ig ig2 lv_score] = scoreDoc(my_new_counts',mybeta(:,:,1),myphi,myx,sigma,alpha,dig_sig);\n lv_score = lv_score + q_a * (a_log_prior - log_q_a)';\n score = word_score + lv_score;\n \n iter = updateIterator(iter,score);\n end\n iter_ctr = iter_ctr + 1;\nend\n%compute output counts for real\nif nargout >= 3\n out_counts = zeros(W,K,A);\n for k=1:K, for a=1:A, out_counts(mydudes,k,a) = myphi(:,k) .* myx' .* q_a(a); end; end\nend\nend", "meta": {"author": "jacobeisenstein", "repo": "SAGE", "sha": "5776655f6c09f2c24a96485a0985660e64664415", "save_path": "github-repos/MATLAB/jacobeisenstein-SAGE", "path": "github-repos/MATLAB/jacobeisenstein-SAGE/SAGE-5776655f6c09f2c24a96485a0985660e64664415/tamEStepNoMex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.8376199673867853, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.39592911827107924}}
{"text": "obSize gives the size.\na = reshape(obSlice,42,51);\nb = flipup(a);\n\n\nfunction [sagSlice,obSlice,sagX,sagY] = ...\n\tmrUpSagShowObl(volume,sagSize,numSlices,curSag,obPts,obSize,obX,obY,volselpts)\n%\n%NAME: [sagSlice,obSlice,sagX,sagY] = ...\n%\tmrUpSagShowObl(volume,sagSize,numSlices,curSag,obPts,obSize,obX,obY,volselpts)\n%AUTHOR: Poirson \n%DATE: 08.07.96\n%HISTORY Started with mrUpSagShowObl.m\n%BUGS:\n\n% relevant code to display the interpolated oblique plane\nglobal obwin\nif ~isempty(obPts)\n\tfigure(obwin);\n\t[obSlice,sagX,sagY] = ...\n\t\tmrDispOblVol(volume,sagSize,numSlices,obPts,obSize,curSag,volselpts);\nend\n\nreturn\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [obSlice, sagX, sagY] = mrDispOblVol(volume,sagSize,numSlices,obPts,obSize,curSag,volselpts)\n%\nglobal obwin volslimin2 volslimax2;\n\nif ~isempty(obPts)\n\tsagX = [curSag,curSag];\n\tsagY = [0,obSize(1)];\n\ttmp = volume;\n\tif ~isempty(volselpts)\n\t\ttmp(volselpts) = -1*ones(1,length(volselpts));\n\tend\n\tobSlice = mrExtractImgVol(tmp, sagSize, numSlices, obPts);\n\tfigure(obwin);\n\tmyShowImageVol(obSlice,obSize,max(obSlice)*get(volslimin2,'value'),max(obSlice)*get(volslimax2,'value'),sagX,sagY);\nend\n\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrAlign/volume/mrFlipOblUpDown.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316991792861, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.39592882991734935}}
{"text": "%PNMDEMO Demonstration of portable bitmap utilities.\n\n% Author: Peter J. Acklam\n% Time-stamp: 1998-05-11 16:39:20\n% E-mail: jacklam@math.uio.no (Internet)\n% URL: http://www.math.uio.no/~jacklam\n\nmore off;\necho on;\nhome; clc;\n%\n% First, read the portable pixelmap with the Matlab logo.\n%\n% The image may be read as an RGB image.\n%\n\n[ r, g, b ] = ppmread( 'logo5' );\n\npause\n\n%\n% The image may also be read as an indexed image.\n%\n\n[ x, map ] = ppmread( 'logo5' );\n\npause\n\n%\n% Since PPMREAD does not simplify the color map automatically, the number\n% of colors in the map equals the number of pixels in the image.\n%\n\npixels_in_image = prod( size(x) )\ncolors_in_map = size( map, 1 )\n\npause\n\n%\n% Use IM2IND to convert intensity images, indexed images and RGB images\n% to indexed images with the smallest possible color map.\n%\n\n[ x, map ] = im2ind( x, map );\n\npause\n\n%\n% Now we see the number of unique colors in the image. The number of\n% colors in the map has been reduced significantly.\n%\n\ncolors_in_map = size( map, 1 )\n\npause\n\n%\n% Display the image.\n%\n\nfigure( gcf ); clf;\ncolormap( map ); image( x ); axis image;\n\npause\n\n%\n% Write the image as a portable graymap.\n% PGMWRITE automatically converts color images to grayscale images.\n% For speed, we use binary (raw) encoding.\n%\n\npgmwrite( x, map, 'logo5', 'binary' );\n\npause\n\n%\n% Read the image. We can use both PGMREAD and PPMREAD for this.\n% PGMREAD can read the image as an intensity image or an indexed image.\n% We choose the latter.\n%\n\n[ x, map ] = pgmread( 'logo5' );\n\npause\n\n%\n% Display the image.\n%\n\nfigure( gcf ); clf;\ncolormap( map ); image( x ); axis image;\n\npause\n\n%\n% As with PPMREAD, PGMREAD does not simplify the color map\n% automatically, so the number of colors in the map may be larger than\n% the number of colors used in the image.\n%\n\ncolors_in_map = size( map, 1 )\n\npause\n\n%\n% Again, we use IM2IND to get the indexed image with the smallest\n% possible color map.\n%\n\n[ x, map ] = im2ind( x, map );\n\npause\n\n%\n% Now we see the number of unique colors in the image.\n%\n\ncolors_in_map = size( map, 1 )\n\npause\n\n%\n% Now write the image as a portable bitmap.\n% PBMWRITE automatically converts color images and grayscale images to\n% black and white images. For speed, we use binary (raw) encoding.\n%\n\npbmwrite( x, map, 'logo5', 'binary' );\n\npause\n\n%\n% Read the image. We can use both PBMREAD, PGMREAD and PPMREAD to this.\n% PBMREAD can read the image as a black and white image or as an indexed\n% image. We choose the latter.\n%\n\n[ x, map ] = pbmread( 'logo5' );\n\npause\n\n%\n% Display the image.\n%\n\nfigure( gcf ); clf;\ncolormap( map ); image( x ); axis image;\n\npause\n\n%\n% That should be all for now, so clean up.\n%\n\ndelete logo5.pgm logo5.pbm\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/134-pnm/pnm/pnmdemo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.39592882991734935}}
{"text": "function covering = getBestCovering(seg, regions, spseg, do_approx)\n% covering = getBestCovering(seg, regions, spseg)\n%\n% Computes covering of seg by regions, where seg is an image with indices\n% denoting a partitioning and regions is a cell array containing indices\n% into spseg specifying image regions.\n%\n% covering.pix = covering weighted by pixel area of seg regions\n% covering.unweighted = average covering (unweighted)\n\nif ~exist('do_approx', 'var')\n do_approx = 0;\nend\n\ncovering.maxov = zeros(max(seg(:)), 1);\ncovering.maxr = zeros(max(seg(:)), 1);\ncovering.area = 0;\ncovering.pix = 0;\ncovering.unweighted = 0;\n\n\nrmap = false(max(spseg(:)), 1);\nif do_approx % approximates seg with spseg\n s = regionprops(spseg, 'Area');\n area = cat(1, s.Area); area = area/sum(area); \n lab = transferRegionLabels(seg, spseg);\n for r1 = 1:max(lab)\n region1 = find(lab==r1); \n maxov = 0;\n maxr = 0; \n for r2 = 1:numel(regions)\n ov = regionOverlap(region1, regions{r2}, area);\n if ov > maxov\n maxov = ov;\n maxr = r2;\n end\n end\n if maxr~=0\n rmap(:) = false;\n rmap(regions{maxr}) = true;\n region1 = seg==r1;\n region2 = rmap(spseg);\n ov = sum(region1(:) & region2(:)) / sum(region1(:) | region2(:)); \n covering.maxov(r1) = ov;\n covering.pix = covering.pix + ov * mean(region1(:)); \n covering.unweighted = covering.unweighted + ov / max(seg(:)); \n covering.area (r1) = mean(region1(:));\n covering.maxr(r1) = maxr;\n end\n \n end\nelse\n stats = regionprops(spseg, 'Area');\n area = cat(1, stats.Area);\n seg(seg<0) = 0;\n stats = regionprops(seg, 'Area');\n segarea = cat(1, stats.Area);\n nsp = numel(area);\n nseg = max(seg(:));\n count = zeros(nsp, nseg);\n ind = find((spseg > 0) & (seg>0));\n for k = ind(:)'\n s1 = spseg(k);\n s2 = seg(k);\n count(s1, s2) = count(s1, s2)+1;\n end\n for r1 = 1:nseg \n maxr = 0;\n maxov = 0; \n for r2 = 1:numel(regions) \n\t region = regions{r2}; region = region(region maxov\n maxr = r2;\n maxov = ov;\n end\n end\n covering.maxr(r1) = maxr;\n covering.regions{r1} = regions{maxr};\n covering.maxov(r1) = maxov;\n covering.area(r1) = segarea(r1)/numel(seg);\n covering.pix = covering.pix + segarea(r1)*maxov/sum(segarea); \n covering.unweighted = covering.unweighted + maxov / nseg; \n end \n \n% rmap = false(max(spseg(:)), 1);\n% for r1 = 1:max(seg(:))\n% region1 = seg==r1; \n% maxov = 0; \n% for r2 = 1:numel(regions) \n% rmap(:) = false;\n% rmap(regions{r2}) = true;\n% region2 = rmap(spseg);\n% ov = sum(region1(:) & region2(:)) / sum(region1(:) | region2(:));\n% if ov > maxov\n% maxov = ov;\n% end\n% end\n% covering = covering + mean(region1(:))*maxov; \n% end \nend\n", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/endres/proposals/src/iccv07Final/src/occlusion/getBestCovering.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.3959288299173493}}
{"text": "function [ total_bboxes ] = apply_correction( total_bboxes, corrections, add1 )\n%APPLY_CORRECTION Summary of this function goes here\n% Detailed explanation goes here\n\n % Perform correction based on regression values\n bbw = total_bboxes(:,3) - total_bboxes(:,1);\n bbh = total_bboxes(:,4) - total_bboxes(:,2);\n \n % TODO is this needed?\n if(add1)\n bbw = bbw + 1;\n bbh = bbh + 1;\n end\n \n new_min_x = total_bboxes(:,1) + corrections(:,1) .* bbw;\n new_min_y = total_bboxes(:,2) + corrections(:,2) .* bbh; \n new_max_x = total_bboxes(:,3) + corrections(:,3) .* bbw;\n new_max_y = total_bboxes(:,4) + corrections(:,4) .* bbh;\n score = total_bboxes(:,5);\n total_bboxes = [new_min_x, new_min_y, new_max_x, new_max_y, score];\n\nend\n\n", "meta": {"author": "TadasBaltrusaitis", "repo": "OpenFace", "sha": "3d4b5cf8d96138be42bed229447f36cbb09a5a29", "save_path": "github-repos/MATLAB/TadasBaltrusaitis-OpenFace", "path": "github-repos/MATLAB/TadasBaltrusaitis-OpenFace/OpenFace-3d4b5cf8d96138be42bed229447f36cbb09a5a29/matlab_version/face_detection/mtcnn/apply_correction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.3958645218925018}}
{"text": "function drawAhmPnt(MapFig, Lmk, color, MapOpt)\n\n% DRAWAHMPNT Draw anchored Homogeneous point landmark in MapFig.\n\n% Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n\nglobal Map\n\nposOffset = [0;0;.2];\n\n% transform to Euclidean\n[x,P] = propagateUncertainty( ...\n Map.x(Lmk.state.r), ...\n Map.P(Lmk.state.r,Lmk.state.r), ...\n @ahm2euc);\n\n% draw\ndrawPnt (MapFig.Lmk(Lmk.lmk).mean, x, color.mean)\nif MapOpt.showEllip\n drawEllipse(MapFig.Lmk(Lmk.lmk).ellipse, x, P, color.ellip)\nend\nif MapOpt.showLmkId\n drawLabel (MapFig.Lmk(Lmk.lmk).label, x+posOffset, num2str(Lmk.id))\nend\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/Graphics/drawAhmPnt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191214879991, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.39586451502670217}}
{"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 varargout = htmlcal(startdate,stopdate,htmlfile,days)\n% HTMLCAL Create an HTML calendar for a range of months.\n% HTMLCAL(FIRSTMONTH,LASTMONTH) creates an HTML file with one or more\n% monthly calendars. Use 'mm/yyyy' or 'mm-yyyy' strings to specify the\n% months. You will be prompted for the name of the output file, whose\n% name will be returned as output if any output variable is given.\n%\n% HTMLCAL(FIRSTMONTH,LASTMONTH,HTMLFILE) also specifies the name of the\n% output file.\n%\n% HTMLCAL(FIRSTMONTH,LASTMONTH,HTMLFILE,DAYS) allows you to specify\n% which days of the week are included, as a length-7 logical vector\n% starting with Sunday. The default is [0 1 1 1 1 1 0], for M-F.\n%\n% HTMLCAL by itself prompts for the first and last month as well as the\n% file name, and offers to show the calendar in a web browser. \n%\n% See also DATENUM, DATEVEC.\n\n% Copyright 2005 by Toby Driscoll. \n% Created 20 January 2005. \n% 30 August 2007 -- documentation added, style tweaked\n\nif nargin < 2\n if nargin < 1\n dv = datevec(date);\n default = sprintf('%i/%i',dv(2),dv(1));\n startdate = input(['First month (',default,')? '],'s');\n if isempty(startdate), startdate = default; end\n default = startdate;\n stopdate = input(['Last month (',default,')? '],'s');\n if isempty(stopdate), stopdate = default; end\n else\n stopdate = startdate;\n end\nend\n \nif nargin < 3 || isempty(htmlfile)\n [fn,pn] = uiputfile( {'*.html','HTML Files'}, ...\n 'Select output file');\n if isequal(fn,0) || isequal(pn,0)\n error('No output file selected.')\n else\n htmlfile = fullfile(pn,fn);\n end\nend\n\nif nargin < 4 || isempty(days)\n days = logical([ 0 1 1 1 1 1 0 ]);\nelseif ischar(days)\n % This allows the \"command syntax\" to work consistently.\n days = eval(days); \nend\ndays = days(:).';\n\nmth = {'January','February','March','April','May','June',...\n 'July','August','September','October','November','December'};\ndow = {'Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'};\n\n% Parse dates.\n[m0,startdate] = strtok(startdate,'/-');\n[y0,startdate] = strtok(startdate,'/-');\n[m1,stopdate] = strtok(stopdate,'/-');\n[y1,stopdate] = strtok(stopdate,'/-');\n\nm0 = str2double(m0); m1 = str2double(m1);\ny0 = str2double(y0); y1 = str2double(y1);\nif any(isnan([m0 y0 m1 y1]))\n error('Invalid month specification.')\nend\n\n% Open output file and write headers.\noutfile = CreateHTMLFile(htmlfile);\n\n% Walk through month by month.\nm1 = m1 + 12*(y1-y0);\t\t\t% account for year-end boundaries\nnumdays = sum(days);\nfor m = m0:m1\n Month = rem(m-1,12) + 1;\n Year = y0 + floor(m/13);\n MonthName = mth{Month};\n\n cal = calendar(Year,Month);\n\n select = false(size(cal));\n select(:,days) = 1; % include these days\n select(~cal) = 0;\t\t\t% but not those outside the\n % actual month\n \n % Begin table in output.\n fmt = '