text:
function [methodinfo,structs,enuminfo,ThunkLibName]=remoteApiProto
%REMOTEAPIPROTO Create structures to define interfaces found in 'extApi'.

%This function was generated by loadlibrary.m parser version 1.1.6.32
%perl options:'extApi.i -outfile=remoteApiProto.m'
ival={cell(1,0)}; % change 0 to the actual number of functions to preallocate the data.
structs=[];enuminfo=[];fcnNum=1;
fcns=struct('name',ival,'calltype',ival,'LHS',ival,'RHS',ival,'alias',ival);
ThunkLibName=[];

% extern  simxInt mtlb_simxSetJointPosition ( simxInt clientID , simxInt jointHandle , simxFloat* position , simxInt operationMode );
fcns.name{fcnNum}='mtlb_simxSetJointPosition'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt mtlb_simxSetJointTargetVelocity ( simxInt clientID , simxInt jointHandle , simxFloat* targetVelocity , simxInt operationMode );
fcns.name{fcnNum}='mtlb_simxSetJointTargetVelocity'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt mtlb_simxSetJointTargetPosition ( simxInt clientID , simxInt jointHandle , simxFloat* targetPosition , simxInt operationMode );
fcns.name{fcnNum}='mtlb_simxSetJointTargetPosition'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt mtlb_simxSetJointForce ( simxInt clientID , simxInt jointHandle , simxFloat* force , simxInt operationMode );
fcns.name{fcnNum}='mtlb_simxSetJointForce'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt mtlb_simxSetFloatSignal ( simxInt clientID , const simxChar * signalName , simxFloat* signalValue , simxInt operationMode );
fcns.name{fcnNum}='mtlb_simxSetFloatSignal'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt mtlb_simxSetObjectFloatParameter ( simxInt clientID , simxInt objectHandle , simxInt parameterID , simxFloat* parameterValue , simxInt operationMode );
fcns.name{fcnNum}='mtlb_simxSetObjectFloatParameter'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt mtlb_simxSetFloatingParameter ( simxInt clientID , simxInt paramIdentifier , simxFloat* paramValue , simxInt operationMode );
fcns.name{fcnNum}='mtlb_simxSetFloatingParameter'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt mtlb_simxCreateDummy ( simxInt clientID , simxFloat* size , const simxUChar * colors , simxInt * objectHandle , simxInt operationMode );
fcns.name{fcnNum}='mtlb_simxCreateDummy'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'singlePtr', 'uint8Ptr', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;

% extern  simxInt mtlb_simxReadProximitySensor(simxInt* clientIDandSensorHandle,simxUChar* detectionState,simxFloat* detectedPoint,simxInt* detectedObjectHandle,simxFloat* detectedSurfaceNormalVector,simxInt operationMode);
fcns.name{fcnNum}='mtlb_simxReadProximitySensor'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32Ptr', 'uint8Ptr', 'singlePtr', 'int32Ptr', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt mtlb_simxAuxiliaryConsoleOpen(simxInt* clientIDandMaxLinesAndModeAndPositionAndSize,const simxChar* title,simxFloat* textColor,simxFloat* backgroundColor,simxInt* consoleHandle,simxInt operationMode);
fcns.name{fcnNum}='mtlb_simxAuxiliaryConsoleOpen'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32Ptr', 'int8Ptr', 'singlePtr', 'singlePtr', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt mtlb_simxDisplayDialog(simxInt* clientIDandDlgTypeAndOperationMode,const simxChar* titleText,const simxChar* mainText,const simxChar* initialText,const simxFloat* titleColorsAndDlgColors,simxInt* dialogHandleAndUiHandle);
fcns.name{fcnNum}='mtlb_simxDisplayDialog'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32Ptr', 'int8Ptr', 'int8Ptr','int8Ptr', 'singlePtr', 'int32Ptr'};fcnNum=fcnNum+1;
% extern  simxInt mtlb_simxQuery(simxInt* clientIDandSignalLengthAndTimeOutInMs,const simxChar* signalName,const simxUChar* signalValue,const simxChar* retSignalName,simxUChar** retSignalValue,simxInt* retSignalLength);
fcns.name{fcnNum}='mtlb_simxQuery'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32Ptr', 'int8Ptr', 'uint8Ptr', 'int8Ptr', 'uint8PtrPtr', 'int32Ptr'};fcnNum=fcnNum+1;
% extern  simxInt mtlb_simxGetObjectGroupData(simxInt* clientIDandObjectTypeAndDataTypeAndOperationMode,simxInt* handlesCountAndIntDataCountAndFloatDataCountAndStringDataCount,simxInt** handles,simxInt** intData,simxFloat** floatData,simxChar** stringData);
fcns.name{fcnNum}='mtlb_simxGetObjectGroupData'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32Ptr', 'int32Ptr', 'int32PtrPtr', 'int32PtrPtr', 'singlePtrPtr', 'int8PtrPtr'};fcnNum=fcnNum+1;

% extern  simxInt simxGetJointPosition ( simxInt clientID , simxInt jointHandle , simxFloat * position , simxInt operationMode );
fcns.name{fcnNum}='simxGetJointPosition'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetJointMatrix ( simxInt clientID , simxInt jointHandle , simxFloat * matrix , simxInt operationMode );
fcns.name{fcnNum}='simxGetJointMatrix'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSetSphericalJointMatrix ( simxInt clientID , simxInt jointHandle , simxFloat * matrix , simxInt operationMode );
fcns.name{fcnNum}='simxSetSphericalJointMatrix'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetJointForce ( simxInt clientID , simxInt jointHandle , simxFloat * force , simxInt operationMode );
fcns.name{fcnNum}='simxGetJointForce'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxReadForceSensor ( simxInt clientID , simxInt forceSensorHandle , simxUChar * state , simxFloat * forceVector , simxFloat * torqueVector , simxInt operationMode );
fcns.name{fcnNum}='simxReadForceSensor'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'uint8Ptr', 'singlePtr', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxBreakForceSensor ( simxInt clientID , simxInt forceSensorHandle , simxInt operationMode );
fcns.name{fcnNum}='simxBreakForceSensor'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxReadVisionSensor ( simxInt clientID , simxInt sensorHandle , simxUChar * detectionState , simxFloat ** auxValues , simxInt ** auxValuesCount , simxInt operationMode );
fcns.name{fcnNum}='simxReadVisionSensor'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'uint8Ptr', 'singlePtrPtr', 'int32PtrPtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetObjectHandle ( simxInt clientID , const simxChar * objectName , simxInt * handle , simxInt operationMode );
fcns.name{fcnNum}='simxGetObjectHandle'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetVisionSensorImage ( simxInt clientID , simxInt sensorHandle , simxInt * resolution , simxUChar ** image , simxUChar options , simxInt operationMode );
fcns.name{fcnNum}='simxGetVisionSensorImage'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32Ptr', 'uint8PtrPtr', 'uint8', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSetVisionSensorImage ( simxInt clientID , simxInt sensorHandle , simxUChar * image , simxInt bufferSize , simxUChar options , simxInt operationMode );
fcns.name{fcnNum}='simxSetVisionSensorImage'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'uint8Ptr', 'int32', 'uint8', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetVisionSensorDepthBuffer ( simxInt clientID , simxInt sensorHandle , simxInt * resolution , simxFloat ** buffer , simxInt operationMode );
fcns.name{fcnNum}='simxGetVisionSensorDepthBuffer'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32Ptr', 'singlePtrPtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetObjectChild ( simxInt clientID , simxInt parentObjectHandle , simxInt childIndex , simxInt * childObjectHandle , simxInt operationMode );
fcns.name{fcnNum}='simxGetObjectChild'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetObjectParent ( simxInt clientID , simxInt childObjectHandle , simxInt * parentObjectHandle , simxInt operationMode );
fcns.name{fcnNum}='simxGetObjectParent'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxLoadModel ( simxInt clientID , const simxChar * modelPathAndName , simxUChar options , simxInt * baseHandle , simxInt operationMode );
fcns.name{fcnNum}='simxLoadModel'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'uint8', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxLoadUI ( simxInt clientID , const simxChar * uiPathAndName , simxUChar options , simxInt * count , simxInt ** uiHandles , simxInt operationMode );
fcns.name{fcnNum}='simxLoadUI'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'uint8', 'int32Ptr', 'int32PtrPtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxLoadScene ( simxInt clientID , const simxChar * scenePathAndName , simxUChar options , simxInt operationMode );
fcns.name{fcnNum}='simxLoadScene'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'uint8', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxStartSimulation ( simxInt clientID , simxInt operationMode );
fcns.name{fcnNum}='simxStartSimulation'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxPauseSimulation ( simxInt clientID , simxInt operationMode );
fcns.name{fcnNum}='simxPauseSimulation'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxStopSimulation ( simxInt clientID , simxInt operationMode );
fcns.name{fcnNum}='simxStopSimulation'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetUIHandle ( simxInt clientID , const simxChar * uiName , simxInt * handle , simxInt operationMode );
fcns.name{fcnNum}='simxGetUIHandle'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetUISlider ( simxInt clientID , simxInt uiHandle , simxInt uiButtonID , simxInt * position , simxInt operationMode );
fcns.name{fcnNum}='simxGetUISlider'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSetUISlider ( simxInt clientID , simxInt uiHandle , simxInt uiButtonID , simxInt position , simxInt operationMode );
fcns.name{fcnNum}='simxSetUISlider'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32', 'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetUIEventButton ( simxInt clientID , simxInt uiHandle , simxInt * uiEventButtonID , simxInt * auxValues , simxInt operationMode );
fcns.name{fcnNum}='simxGetUIEventButton'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32Ptr', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetUIButtonProperty ( simxInt clientID , simxInt uiHandle , simxInt uiButtonID , simxInt * prop , simxInt operationMode );
fcns.name{fcnNum}='simxGetUIButtonProperty'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSetUIButtonProperty ( simxInt clientID , simxInt uiHandle , simxInt uiButtonID , simxInt prop , simxInt operationMode );
fcns.name{fcnNum}='simxSetUIButtonProperty'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32', 'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxAddStatusbarMessage ( simxInt clientID , const simxChar * message , simxInt operationMode );
fcns.name{fcnNum}='simxAddStatusbarMessage'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxAuxiliaryConsoleClose ( simxInt clientID , simxInt consoleHandle , simxInt operationMode );
fcns.name{fcnNum}='simxAuxiliaryConsoleClose'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxAuxiliaryConsolePrint ( simxInt clientID , simxInt consoleHandle , const simxChar * txt , simxInt operationMode );
fcns.name{fcnNum}='simxAuxiliaryConsolePrint'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int8Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxAuxiliaryConsoleShow ( simxInt clientID , simxInt consoleHandle , simxUChar showState , simxInt operationMode );
fcns.name{fcnNum}='simxAuxiliaryConsoleShow'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'uint8', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetObjectOrientation ( simxInt clientID , simxInt objectHandle , simxInt relativeToObjectHandle , simxFloat * eulerAngles , simxInt operationMode );
fcns.name{fcnNum}='simxGetObjectOrientation'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetObjectPosition ( simxInt clientID , simxInt objectHandle , simxInt relativeToObjectHandle , simxFloat * position , simxInt operationMode );
fcns.name{fcnNum}='simxGetObjectPosition'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSetObjectOrientation ( simxInt clientID , simxInt objectHandle , simxInt relativeToObjectHandle , const simxFloat * eulerAngles , simxInt operationMode );
fcns.name{fcnNum}='simxSetObjectOrientation'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSetObjectPosition ( simxInt clientID , simxInt objectHandle , simxInt relativeToObjectHandle , const simxFloat * position , simxInt operationMode );
fcns.name{fcnNum}='simxSetObjectPosition'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSetObjectParent ( simxInt clientID , simxInt objectHandle , simxInt parentObject , simxUChar keepInPlace , simxInt operationMode );
fcns.name{fcnNum}='simxSetObjectParent'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32', 'uint8', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSetUIButtonLabel ( simxInt clientID , simxInt uiHandle , simxInt uiButtonID , const simxChar * upStateLabel , const simxChar * downStateLabel , simxInt operationMode );
fcns.name{fcnNum}='simxSetUIButtonLabel'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32', 'int8Ptr', 'int8Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetLastErrors ( simxInt clientID , simxInt * errorCnt , simxChar ** errorStrings , simxInt operationMode );
fcns.name{fcnNum}='simxGetLastErrors'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32Ptr', 'int8PtrPtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetArrayParameter ( simxInt clientID , simxInt paramIdentifier , simxFloat * paramValues , simxInt operationMode );
fcns.name{fcnNum}='simxGetArrayParameter'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSetArrayParameter ( simxInt clientID , simxInt paramIdentifier , const simxFloat * paramValues , simxInt operationMode );
fcns.name{fcnNum}='simxSetArrayParameter'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetBooleanParameter ( simxInt clientID , simxInt paramIdentifier , simxUChar * paramValue , simxInt operationMode );
fcns.name{fcnNum}='simxGetBooleanParameter'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'uint8Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSetBooleanParameter ( simxInt clientID , simxInt paramIdentifier , simxUChar paramValue , simxInt operationMode );
fcns.name{fcnNum}='simxSetBooleanParameter'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'uint8', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetIntegerParameter ( simxInt clientID , simxInt paramIdentifier , simxInt * paramValue , simxInt operationMode );
fcns.name{fcnNum}='simxGetIntegerParameter'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSetIntegerParameter ( simxInt clientID , simxInt paramIdentifier , simxInt paramValue , simxInt operationMode );
fcns.name{fcnNum}='simxSetIntegerParameter'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetFloatingParameter ( simxInt clientID , simxInt paramIdentifier , simxFloat * paramValue , simxInt operationMode );
fcns.name{fcnNum}='simxGetFloatingParameter'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetStringParameter ( simxInt clientID , simxInt paramIdentifier , simxChar ** paramValue , simxInt operationMode );
fcns.name{fcnNum}='simxGetStringParameter'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int8PtrPtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetCollisionHandle ( simxInt clientID , const simxChar * collisionObjectName , simxInt * handle , simxInt operationMode );
fcns.name{fcnNum}='simxGetCollisionHandle'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetDistanceHandle ( simxInt clientID , const simxChar * distanceObjectName , simxInt * handle , simxInt operationMode );
fcns.name{fcnNum}='simxGetDistanceHandle'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxReadCollision ( simxInt clientID , simxInt collisionObjectHandle , simxUChar * collisionState , simxInt operationMode );
fcns.name{fcnNum}='simxReadCollision'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'uint8Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxReadDistance ( simxInt clientID , simxInt distanceObjectHandle , simxFloat * minimumDistance , simxInt operationMode );
fcns.name{fcnNum}='simxReadDistance'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxRemoveObject ( simxInt clientID , simxInt objectHandle , simxInt operationMode );
fcns.name{fcnNum}='simxRemoveObject'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxRemoveModel ( simxInt clientID , simxInt objectHandle , simxInt operationMode );
fcns.name{fcnNum}='simxRemoveModel'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxRemoveUI ( simxInt clientID , simxInt uiHandle , simxInt operationMode );
fcns.name{fcnNum}='simxRemoveUI'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxCloseScene ( simxInt clientID , simxInt operationMode );
fcns.name{fcnNum}='simxCloseScene'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetObjects ( simxInt clientID , simxInt objectType , simxInt * objectCount , simxInt ** objectHandles , simxInt operationMode );
fcns.name{fcnNum}='simxGetObjects'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32Ptr', 'int32PtrPtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxEndDialog ( simxInt clientID , simxInt dialogHandle , simxInt operationMode );
fcns.name{fcnNum}='simxEndDialog'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetDialogInput ( simxInt clientID , simxInt dialogHandle , simxChar ** inputText , simxInt operationMode );
fcns.name{fcnNum}='simxGetDialogInput'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int8PtrPtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetDialogResult ( simxInt clientID , simxInt dialogHandle , simxInt * result , simxInt operationMode );
fcns.name{fcnNum}='simxGetDialogResult'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxCopyPasteObjects ( simxInt clientID , const simxInt * objectHandles , simxInt objectCount , simxInt ** newObjectHandles , simxInt * newObjectCount , simxInt operationMode );
fcns.name{fcnNum}='simxCopyPasteObjects'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32Ptr', 'int32', 'int32PtrPtr', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetObjectSelection ( simxInt clientID , simxInt ** objectHandles , simxInt * objectCount , simxInt operationMode );
fcns.name{fcnNum}='simxGetObjectSelection'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32PtrPtr', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSetObjectSelection ( simxInt clientID , const simxInt * objectHandles , simxInt objectCount , simxInt operationMode );
fcns.name{fcnNum}='simxSetObjectSelection'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32Ptr', 'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxClearFloatSignal ( simxInt clientID , const simxChar * signalName , simxInt operationMode );
fcns.name{fcnNum}='simxClearFloatSignal'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxClearIntegerSignal ( simxInt clientID , const simxChar * signalName , simxInt operationMode );
fcns.name{fcnNum}='simxClearIntegerSignal'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxClearStringSignal ( simxInt clientID , const simxChar * signalName , simxInt operationMode );
fcns.name{fcnNum}='simxClearStringSignal'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetFloatSignal ( simxInt clientID , const simxChar * signalName , simxFloat * signalValue , simxInt operationMode );
fcns.name{fcnNum}='simxGetFloatSignal'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetIntegerSignal ( simxInt clientID , const simxChar * signalName , simxInt * signalValue , simxInt operationMode );
fcns.name{fcnNum}='simxGetIntegerSignal'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetStringSignal ( simxInt clientID , const simxChar * signalName , simxUChar ** signalValue , simxInt * signalLength , simxInt operationMode );
fcns.name{fcnNum}='simxGetStringSignal'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'uint8PtrPtr', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetAndClearStringSignal ( simxInt clientID , const simxChar * signalName , simxUChar ** signalValue , simxInt * signalLength , simxInt operationMode );
fcns.name{fcnNum}='simxGetAndClearStringSignal'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'uint8PtrPtr', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxReadStringStream ( simxInt clientID , const simxChar * signalName , simxUChar ** signalValue , simxInt * signalLength , simxInt operationMode );
fcns.name{fcnNum}='simxReadStringStream'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'uint8PtrPtr', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSetIntegerSignal ( simxInt clientID , const simxChar * signalName , simxInt signalValue , simxInt operationMode );
fcns.name{fcnNum}='simxSetIntegerSignal'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSetStringSignal ( simxInt clientID , const simxChar * signalName , const simxUChar * signalValue , simxInt signalLength , simxInt operationMode );
fcns.name{fcnNum}='simxSetStringSignal'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'uint8Ptr', 'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxAppendStringSignal ( simxInt clientID , const simxChar * signalName , const simxUChar * signalValue , simxInt signalLength , simxInt operationMode );
fcns.name{fcnNum}='simxAppendStringSignal'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'uint8Ptr', 'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxWriteStringStream ( simxInt clientID , const simxChar * signalName , const simxUChar * signalValue , simxInt signalLength , simxInt operationMode );
fcns.name{fcnNum}='simxWriteStringStream'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'uint8Ptr', 'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetObjectFloatParameter ( simxInt clientID , simxInt objectHandle , simxInt parameterID , simxFloat * parameterValue , simxInt operationMode );
fcns.name{fcnNum}='simxGetObjectFloatParameter'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetObjectIntParameter ( simxInt clientID , simxInt objectHandle , simxInt parameterID , simxInt * parameterValue , simxInt operationMode );
fcns.name{fcnNum}='simxGetObjectIntParameter'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSetObjectIntParameter ( simxInt clientID , simxInt objectHandle , simxInt parameterID , simxInt parameterValue , simxInt operationMode );
fcns.name{fcnNum}='simxSetObjectIntParameter'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32', 'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetModelProperty ( simxInt clientID , simxInt objectHandle , simxInt * prop , simxInt operationMode );
fcns.name{fcnNum}='simxGetModelProperty'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32Ptr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSetModelProperty ( simxInt clientID , simxInt objectHandle , simxInt prop , simxInt operationMode );
fcns.name{fcnNum}='simxSetModelProperty'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetObjectVelocity ( simxInt clientID , simxInt objectHandle , simxFloat * linearVelocity , simxFloat * angularVelocity , simxInt operationMode );
fcns.name{fcnNum}='simxGetObjectVelocity'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'singlePtr', 'singlePtr', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxStart ( const simxChar * connectionAddress , simxInt connectionPort , simxUChar waitUntilConnected , simxUChar doNotReconnectOnceDisconnected , simxInt timeOutInMs , simxInt commThreadCycleInMs );
fcns.name{fcnNum}='simxStart'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int8Ptr', 'int32', 'uint8', 'uint8', 'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxVoid simxFinish ( simxInt clientID );
fcns.name{fcnNum}='simxFinish'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}=[]; fcns.RHS{fcnNum}={'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxGetPingTime ( simxInt clientID , simxInt * pingTime );
fcns.name{fcnNum}='simxGetPingTime'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32Ptr'};fcnNum=fcnNum+1;
% extern  simxInt simxGetLastCmdTime ( simxInt clientID );
fcns.name{fcnNum}='simxGetLastCmdTime'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSynchronousTrigger ( simxInt clientID );
fcns.name{fcnNum}='simxSynchronousTrigger'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxSynchronous ( simxInt clientID , simxUChar enable );
fcns.name{fcnNum}='simxSynchronous'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'uint8'};fcnNum=fcnNum+1;
% extern  simxInt simxPauseCommunication ( simxInt clientID , simxUChar pause );
fcns.name{fcnNum}='simxPauseCommunication'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'uint8'};fcnNum=fcnNum+1;
% extern  simxInt simxGetInMessageInfo ( simxInt clientID , simxInt infoType , simxInt * info );
fcns.name{fcnNum}='simxGetInMessageInfo'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32Ptr'};fcnNum=fcnNum+1;
% extern  simxInt simxGetOutMessageInfo ( simxInt clientID , simxInt infoType , simxInt * info );
fcns.name{fcnNum}='simxGetOutMessageInfo'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int32', 'int32Ptr'};fcnNum=fcnNum+1;
% extern  simxInt simxGetConnectionId ( simxInt clientID );
fcns.name{fcnNum}='simxGetConnectionId'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32'};fcnNum=fcnNum+1;
% extern  simxUChar * simxCreateBuffer ( simxInt bufferSize );
fcns.name{fcnNum}='simxCreateBuffer'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='uint8Ptr'; fcns.RHS{fcnNum}={'int32'};fcnNum=fcnNum+1;
% extern  simxVoid simxReleaseBuffer ( simxUChar * buffer );
fcns.name{fcnNum}='simxReleaseBuffer'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}=[]; fcns.RHS{fcnNum}={'uint8Ptr'};fcnNum=fcnNum+1;
% extern  simxInt simxTransferFile ( simxInt clientID , const simxChar * filePathAndName , const simxChar * fileName_serverSide , simxInt timeOut , simxInt operationMode );
fcns.name{fcnNum}='simxTransferFile'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'int8Ptr', 'int32', 'int32'};fcnNum=fcnNum+1;
% extern  simxInt simxEraseFile ( simxInt clientID , const simxChar * fileName_serverSide , simxInt operationMode );
fcns.name{fcnNum}='simxEraseFile'; fcns.calltype{fcnNum}='cdecl'; fcns.LHS{fcnNum}='int32'; fcns.RHS{fcnNum}={'int32', 'int8Ptr', 'int32'};fcnNum=fcnNum+1;
methodinfo=fcns;

repo: KST-Kuka-Sunrise-Toolbox


text:
function out=sign(x)

precision=x(1).precision;
out_rval=cell(size(x));
out_ival=cell(size(x));

for ii=1:numel(x)
 imag=false;
 [xrval,xival]=getVals(x,ii);

 out_rval{ii}=mpfr_absc(precision,xrval,xival);

 [out_rval{ii},out_ival{ii}]=mpfr_divc(precision,xrval,xival,out_rval{ii},mpExpForm('0',0));

end % for ii=1:max(ex,
out=class(struct('rval',out_rval,...
                  'ival',out_ival,...
                  'precision',precision),'mp');

author: opencobra

repo: cobratoolbox


text:
 function f = nufft_diric(k, N, K, use_true_diric)
%function f = nufft_diric(k, N, K, use_true_diric)
% "regular fourier" Dirichlet-function WITHOUT phase
% diric(t) = sin(pi N t / K) / ( N * sin(pi t / K) )
%	\approx sinc(t / (K/N))
% in:
%	k [...]		sample locations (unitless real numbers)
%	N		signal length
%	K		DFT length
%	use_true_diric	1 = use true Diric function.
%			(default is to use sinc approximation)
% out:
%	f [...]		corresponding function values
%
% Copyright 2001-12-8, Jeff Fessler, The University of Michigan

% default is to plot
if nargin < 3
	help(mfilename)
	kmax = 2 * (10 + 1 * 4);
	k = linspace(-kmax,kmax,201);
	ki = [-kmax:kmax];
	N = 32;
	K = 2*N;
	g = nufft_diric(k, N, K, 1);
	gi = nufft_diric(ki, N, K, 1);
	s = nufft_diric(k, N, K);
	dm = diric((2*pi/K)*k,N);
	plot(k, g, 'y-', k, s, 'c-', k, dm, 'r-', ki, gi, '.'), axis tight
	legend('nufft diric', 'sinc', 'matlab diric')
	xlabel k, ylabel diric(k)
	printf('max %% difference = %g', max_percent_diff(g,s))
	return
end

if nargin < 4
	use_true_diric = logical(0);
end

% diric version
if use_true_diric
	t = (pi/K) * k;
	f = sin(t);
	i = abs(t) > 1e-12;	% nonzero argument
	f(i) = sin(N*t(i)) ./ (N * f(i));
	f(~i) = 1;

% sinc version
else
%	f = sinc(k / (K/N));
	f = nufft_sinc(k / (K/N));
end

% this is faster than matlab's sinc because it does not use "find"
function y = nufft_sinc(x)
y = ones(size(x));
%i = abs(x) > 1e-12;
i = x ~= 0;
x = x(i);
y(i) = sin(pi*x) ./ (pi*x);

author: thomaskuestner


text:
function [fit] = compare_new(varargin)

% Determine list of inputs.
inpn = cell(1, length(varargin));
for kn = 1:length(varargin);
    inpn{kn} = inputname(kn);
end

v = {varargin{:} inpn};
th = idss(v{2});
th = th('y1', cell(0));

z = v{1};
z = iddata(z(:, 1), z(:, 2:end), 1);
y = pvget(z, 'OutputData');
z1 = z(:, 'y1', cell(0));

[yh, x01] = predict(th, z1, 1, 'e');
yhh = pvget(yh, 'OutputData');

%Compute fit.
err = norm(yhh{1} - y{1});
meanerr = norm(y{1} - mean(y{1}));
fit = 100*(1-err/meanerr);

author: alexandrebarachant


text:
function nthreads = SetUpMatlabPoolforJAABAPlot()

% limitations:
% computation_threads >= 1
% framecache_threads >= 1
% computation_threads + framecache_threads <= NumWorkers
% computation_threads <= numCores
% framecache_threads <= numCores

if verLessThan('matlab','8.3.0.532'),

  c=parcluster;
  numCores = feature('numCores');
  NumWorkers = c.NumWorkers;
  matlabpool_size = matlabpool('size');

  % load in rc file
  isrcfile = exist('most_recent_config.mat','file');
  if isrcfile,
    rc=load('most_recent_config.mat');  % would've been nice to be able to just call LoadRC
  else
    rc = struct;
  end

  % if matlabpool has already been started, use this as the number of
  % computation threads
  if matlabpool_size > 0,
    rc.handles.computation_threads = min(matlabpool_size,NumWorkers);
  end

  % if both computation_threads and framecache_threads are set in rc file,
  % just adjust them so that they are legal values
  if isfield(rc,'handles') && isfield(rc.handles,'computation_threads'),
    rc.handles.computation_threads = max(1,min([rc.handles.computation_threads,numCores,NumWorkers]));
  else
    rc.handles.computation_threads = min(numCores,NumWorkers);
  end

  nthreads = rc.handles.computation_threads;
  fprintf('Number of threads allocated for computation: %d\n',nthreads);

  if matlabpool_size>0 && matlabpool_size ~= rc.handles.computation_threads,
    matlabpool close;
    matlabpool_size = matlabpool('size');
  end

  % start up matlabpool if necessary
  if (numCores>1) && (matlabpool_size<1),
    matlabpool('open',rc.handles.computation_threads);
  end

  if isrcfile,
    save('most_recent_config.mat','-struct','rc')
  end
else

  c=parcluster;
  numCores = feature('numCores');
  NumWorkers = c.NumWorkers;
  curpool = gcp('nocreate');
  if isempty(curpool)
    curpool_size = 0;
  else
    curpool_size = curpool.NumWorkers;
  end
  % load in rc file
  isrcfile = exist('most_recent_config.mat','file');
  if isrcfile,
    rc=load('most_recent_config.mat');  % would've been nice to be able to just call LoadRC
  else
    rc = struct;
  end

  % if matlabpool has already been started, use this as the number of
  % computation threads
  if curpool_size > 0,
    rc.handles.computation_threads = min(curpool_size,NumWorkers);
  end

  % if both computation_threads and framecache_threads are set in rc file,
  % just adjust them so that they are legal values
  if isfield(rc,'handles') && isfield(rc.handles,'computation_threads'),
    rc.handles.computation_threads = max(1,min([rc.handles.computation_threads,numCores,NumWorkers]));
  else
    rc.handles.computation_threads = min(numCores,NumWorkers);
  end

  nthreads = rc.handles.computation_threads;
  fprintf('Number of threads allocated for computation: %d\n',nthreads);

  if curpool_size>0 && curpool_size ~= rc.handles.computation_threads,
    delete(gcp);
    curpool_size = 0;
  end

  % start up matlabpool if necessary
  if (numCores>1) && (curpool_size<1),
    parpool(rc.handles.computation_threads);
  end

  if isrcfile,
    save('most_recent_config.mat','-struct','rc')
  end

end

author: kristinbranson

repo: JAABA


text:
function [C,u,IA,IC] = randcycle(A)
  % RANDCYCLE Randomly reindexs a list a indices
  %
  % Inputs:
  %   A  #A list of indices with unique values u
  % Outputs:
  %   C  #C list of indices with same unique values u
  %   u,IA,IC  output of unique(A);
  %

  [u,IA,IC] = unique(A);
  % scramble u
  u = u(randperm(end));
  C = u(IC);
end

author: alecjacobson

repo: gptoolbox


text:
function determ = ortega_determinant ( n, u, v, d )

%*****************************************************************************80
%
%% ORTEGA_DETERMINANT returns the determinant of the ORTEGA matrix.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    06 September 2008
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    James Ortega,
%    Generation of Test Matrices by Similarity Transformations,
%    Communications of the ACM,
%    Volume 7, 1964, pages 377-378.
%
%  Parameters:
%
%    Input, integer N, the order of the matrix.
%    2 <= N.
%
%    Input, real U(N), V(N), vectors which define the matrix.
%    U'V must not equal -1.0.  If, in fact, U'V = 0, and U, V and D are
%    integers, then the matrix, inverse, eigenvalues, and eigenvectors
%    will be integers.
%
%    Input, real D(N), the desired eigenvalues.
%
%    Output, real DETERM, the determinant.
%
  determ = prod ( d(1:n) );

  return
end

author: johannesgerer

repo: jburkardt-m


text:
%   Class for Hi-D matching with merging of data subsets using
%       QF match or F-measure or both
%   This produces a visual table and histogram of dissimilarities and
%   overlaps between subset matches.
%
%   The function getAverages answers the question of overall goodness
%   by returning the median/mean dissimilarity or overlap
%
%
%   QF Algorithm is described in
%   https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6586874/
%   and
%   https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5818510/
%
%   Bioinformatics lead: Darya Orlova <dyorlova@gmail.com>
%   Software Developer: Stephen Meehan <swmeehan@stanford.edu>
%
%   Provided by the Herzenberg Lab at Stanford University
%   License: BSD 3 clause
%
classdef QfTable < handle
    properties
        contextDescription;
        context;
        fcnFpnSubsets;
    end

    properties(SetAccess=private)
        fig;
        data;
        unmatched;
        sortTable;
        tb;
        qf;
        tClrs;
        priorFig;
        fHistFig;
        qHistFig;
        falsePosNegFig;
        otherFigs={};
        R;
    end

    properties(Constant)
        PROP_OUTER_POS2='OuterPosition2_V2';
        DEBUG=false;
    end

    methods
        function this=QfTable(qf, tClrs, props, priorFig, visible)
            if nargin<5
                visible=true;
                if nargin<4
                    priorFig=get(0, 'currentFig');
                    if nargin<3
                        props=[];
                    end
                end
            end
            app=BasicMap.Global;
            if isempty(props)
                props=app;
            end
            this.tClrs=tClrs;
            this.qf=qf;
            PROP_COL_W='mdsColumnWidthsV1.33';
            PROP_COL_ORD='mdsColumnOrder_v2';
            PROP_SORT='mdsRowOrder_v2';
            path=BasicMap.Path;
            if visible
                pu=PopUp('Preparing QF dissimilarity table', 'north west+', ...
                    'Note...', false, true, fullfile(path, 'genieSearch.png'));
            else
                pu=[];
            end
            this.priorFig=priorFig;
            [this.fig, tb_]=Gui.Figure;
            this.tb=tb_;
            figName=['QF dissimilarity  ' ...
                num2str(length(qf.tIds)) ' X ' num2str(length(qf.sIds))...
                ' subsets'];
            set(this.fig, 'CloseRequestFcn', @(h, e)hush(h), ...
                'Name', figName);
            [this.data, labels, fmts, tips,  this.unmatched, groupIdx, ...
                freqIdx, rankIdx, symIdx]=QfTable.Contents(qf, tClrs, pu);
            [this.R, C]=size(this.data);
            J=edu.stanford.facs.swing.Basics;
            [sData, widths]=SortTable.Convert(this.data, fmts);
            this.sortTable=SortTable(this.fig, sData, ...
                labels, [], @(h,e)select(h,e), tips);
            st=this.sortTable;
            jt=st.jtable;
            N=length(widths);
            for i=1:N
                if app.highDef
                    factor=app.toolBarFactor;
                else
                    factor=1;
                end
                st.setColumnWidth(i, widths(i)*factor)
                st.setColumnWidth(i, widths(i)*factor)
            end
            preSorted=SortTable.SetRowOrder(jt, ...
                BasicMap.GetNumbers(props, PROP_SORT));
            if ~preSorted
                jt.sortColumn(rankIdx-1, true, true);
                jt.sortColumn(groupIdx-1, false, true);
                jt.sortColumn(freqIdx-1, false, false);
            end
            startingRowOrder=SortTable.GetRowOrder(jt);
            if ~isempty(qf.matrixHtml)
                ToolBarMethods.addButton(tb_, ...
                    fullfile(path, 'world_16.png'), 'See table in default `r', ...
                    @(h,e)browse(h));
            end
            bb=ToolBarMethods.addButton(tb_,fullfile(path, 'table.gif'), ...
                'Restore default row and column order', ...
                @(h,e)defaultOrder());
            ToolBarMethods.addButton(tb_,fullfile(path, 'leftArrowNarrow.png'), ...
                'Shift sorted columns to the left', ...
                @(h,e)shiftSortLeft());

            ToolBarMethods.addButton(tb_, fullfile(path, 'histQF.png'), ...
                'Open histogram of QF scores', ...
                @(h,e)doHistQF(this));
            ToolBarMethods.addButton(tb_, fullfile(path, 'histF.png'), ...
                'Open histogram of F-measure scores', ...
                @(h,e)doHistF(this, true));
            savedOrder=BasicMap.GetNumbers(props, PROP_COL_ORD);
            if ~isempty(savedOrder)
                try
                    SortTable.SetColumnOrder(jt, savedOrder,...
                        BasicMap.GetNumbers(props, PROP_COL_W));
                catch
                end
            else
                defaultColumnOrder;
            end
            op=BasicMap.GetNumbers(props, QfTable.PROP_OUTER_POS2);
            if length(op)==4
                newFigPos=Gui.RepositionOnSameScreenIfRequired(op);
                set(this.fig, 'OuterPosition', newFigPos);
                Gui.FitFigToScreen(this.fig);
            elseif ~isempty(priorFig)
                Gui.SetToRight(this.priorFig, this.fig, false, 80);
            end
            if visible
                pu.close;
                Gui.SetFigVisible(this.fig);
            end
            if preSorted
                jt.unsort;
                SortTable.SetRowOrder(jt, ...
                    BasicMap.GetNumbers(props, PROP_SORT));
            elseif isempty(savedOrder)
                bb.doClick;
            end
            MatBasics.DoLater(@(h,e)heighten(), .31);
            this.qf.tClrs=this.tClrs;
            try
                if isempty(this.qf.falsePosNegs)
                    this.qf.getFalsePosNegRecords;
                end
                if ~isempty(this.qf.falsePosNegs)
                    try
                        this.qf.getFalsePosNegsTab(false);
                        this.qf.getFalsePosNegSubsets(true);
                    catch
                        %this.qf is a structure and not an instance
                        %so the 2 getFalse*() methods were called and
                        %results are stored in structure
                    end
                    ToolBarMethods.addButton(tb_, ...
                        fullfile(path, 'plusMinus.png'), ...
                        'See false positive/negative results', ...
                        @(h,e)browseFalsePosNeg(this));
                    fpn=this.qf.falsePosNegSubsetsFile;
                    if ~isempty(fpn) && exist(fpn, 'file')
                        ToolBarMethods.addButton(tb_, ...
                            fullfile(path, 'tree.png'), ...
                            'Import false +/- into AutoGate GatingTree', ...
                            @(h,e)importFalsePosNegGates(this));
                    end
                end
            catch ex
                if ~isstruct(this.qf)
                    ex.getReport
                else
                    this.qf.falsePosNegs=[];
                end
            end
            function heighten
                drawnow;
                height=jt.getRowHeight;
                jt.setRowHeight(floor(height*1.33));
                try
                    if props.multiProps.is('mds_figHistQF', false)
                        this.doHistQF(visible);
                    end
                    if props.multiProps.is('mds_figHistF', false)
                        this.doHistF;
                    end
                catch ex
                    %disp('Using QF table outside of CytoGenie''s AutoGate')
                    %ex.getReport
                end
            end

            function shiftSortLeft(h)
                if ~SortTable.MoveSortColumnsLeft(jt)
                    if ismac
                        key='command';
                    else
                        key='control';
                    end
                    msg(Html.Wrap(['There is no sort order currently.'...
                        '
To sort the table you
'...
                        '
Click on a column to sort it'...
                        '
Click again for descending order'...
                        '
Hold ' key ' key for multi column
']), ...
                        8, 'north', 'No sort order...');
                else
                    r=jt.getSelectedRow;
                    if r<0
                        r=0;
                    end
                    rect=jt.getCellRect(r,0, true);
                    jt.scrollRectToVisible(rect);
                end
            end

            function defaultOrder()
                defaultRowOrder;
                defaultColumnOrder;
            end

            function defaultRowOrder
                SortTable.SetRowOrder(jt, [(rankIdx-1) true 0; ...
                    (groupIdx-1) false 0; (freqIdx-1) false 1]);
            end

            function defaultColumnOrder()
                idxs=1:jt.getColumnCount;
                idxs(rankIdx)=[];
                idxs(symIdx)=[];
                idxs=[rankIdx symIdx idxs]-1;
                SortTable.SetColumnOrder(jt, idxs, [], true);
            end

            function browse(h)
                Html.Browse(Html.Wrap([SortTable.ToHtml(jt) '
' ...
                    Html.remove(qf.matrixHtml)]));
            end

            function hush(h)
                if ~isempty(priorFig) && ishandle(this.priorFig)
                    [columnOrder, widths]=SortTable.GetColumnOrder(jt);
                    props.set(PROP_COL_ORD, num2str(columnOrder));
                    props.set(PROP_COL_W, num2str(widths));
                    rowOrder=SortTable.GetRowOrder(jt);
                    if ~isequal(rowOrder, startingRowOrder)
                        props.set(PROP_SORT, MatBasics.Encode(...
                            rowOrder));
                    end
                    props.set(QfTable.PROP_OUTER_POS2, ...
                        num2str(get(h, 'OuterPosition')));
                    figure(this.priorFig);
                    Gui.CloseFigs(this.otherFigs);
                end
                delete(h);
            end

            function showSelected()
                selectedIdxs=SortTable.SelectedRows(jt);
                try
                    N_=length(selectedIdxs);
                    for ii=1:N_

                    end
                catch ex
                    ex.getReport
                end
            end
            function select(h, e)
                if ~isempty(e.Indices)
                    rowIdx=e.Indices(1,1)-1;
                    if rowIdx>=0
                        try
                            colIdx=jt.convertColumnIndexToModel(...
                                e.Indices(1,2)-1);
                            st.showTip(colIdx+1);
                            rowIdx=jt.getActualRowAt(...
                                jt.convertRowIndexToModel(rowIdx))+1;

                            showSelected;
                        catch ex
                            ex.getReport
                        end
                        return;
                    end
                end
                st.showTip(0);
            end
        end

        function [medianDissimilarity, meanDissimilarity, ...
                medianOverlap, meanOverlap]=getAverages(this)
            [~,medianDissimilarity, meanDissimilarity]=this.getData(true);
            [~,medianOverlap, meanOverlap]=this.getData(false);
        end

        function [qfData, mdn, mn]=getData(this, dissimilarity)
            if nargin<2 || dissimilarity
                idx=4;
            else
                idx=5;
            end
            qfData=cell2mat(this.data(:, idx))*100;
            qfData=qfData(~isnan(qfData));
            mdn=median(qfData);
            mn=mean(qfData);
        end

        function browseFalsePosNeg(this)
            if ~isempty(this.falsePosNegFig) ...
                    && ishandle(this.falsePosNegFig)
                figure(this.falsePosNegFig);
                return;
            end
            set(0, 'CurrentFigure', this.fig);
            [fig_,that]=FalsePositiveNegative.Plot([0 1], this.qf.falsePosNegFile);
            this.otherFigs{end+1}=fig_;
            figure(fig_);
            that.fcnImportGates=@()importFalsePosNegGates(this);
            that.fcnMoreHtml=@()getFalsePosNegMatrixHtml(this);
            Gui.Locate (fig_, this.fig, 'north east+');
            this.falsePosNegFig=fig_;
        end

        function html=getFalsePosNegMatrixHtml(this)
            html=FalsePositiveNegative.MatrixHtml(this.qf);
        end

        function importFalsePosNegGates(this)
            fpn=this.qf.falsePosNegSubsetsFile;
            if ~isempty(this.fcnFpnSubsets)
                feval(this.fcnFpnSubsets);
            else
                FalsePositiveNegative.ImportGates(fpn);
            end
        end

        function ok=doHistQF(this, visible)
            if nargin<2
                visible=true;
            end
            ok=true;
            if ishandle(this.qHistFig)
                figure(this.qHistFig);
            else
                fig_=Gui.NewFigure;
                if ~visible
                    set(fig_, 'visible', 'off');
                end
                this.qHistFig=fig_;
                Gui.Resize(fig_, .66);
                Gui.Locate(fig_, this.fig, 'south west+');
                ax=gca;
                [qfData, avgMdn, avgMn]=this.getData;
                if isempty(qfData)
                    ok=false;
                    return;
                end

                histogram(ax, qfData, length(unique(qfData)));
                set(ax, 'units', 'normalized', 'Position', ...
                    [.1 .16 .8 .7]);
                Gui.StretchUpper(ax, @ylim, .1);
                Gui.StretchUpper(ax, @xlim, .1);
                xlabel(ax, '% dissimilarity', 'FontName', 'Arial')
                xlim(ax, [-5 100]);
                ylabel(ax, '# of subset matches', 'FontName', 'Arial')
                figName=['Dissimilarity ' ...
                    num2str(length(this.qf.tIds)) ' X ' ...
                    num2str(length(this.qf.sIds))];
                this.addTitleToHist(fig_, ax, ...
                    figName, avgMdn, avgMn);
                this.addFalsePosNegButton(fig_);
                %disp(num2str(get(fig_, 'OuterPosition')));
                set(fig_, 'CloseRequestFcn', @(h, e)hush(h));
            end

            function hush(h)
                if ishandle(this.fig)
                    figure(this.fig);
                end
                delete(h);
            end
        end

        function addTitleToHist(this, fig, ax, score, avgMdn, avgMn)
            ttl=[score ', median/mean=\color{blue}' ...
                String.encodeRounded(avgMdn, 1) ...
                '\color{black}/\color{blue}'...
                String.encodeRounded(avgMn, 1) '\color{black}% '];
            set(fig, 'name', String.RemoveTex(score), 'NumberTitle', 'off');
            if this.unmatched>0
                title(ax, {ttl, [ ...
                    num2str(this.R-this.unmatched) ' subsets matched, ' ...
                    '\color{red}' num2str(this.unmatched) ...
                    ' \color{black}NOT matched ']},'FontName', 'Arial');
            else
                title(ax, {ttl, [ ...
                    num2str(this.R) ' matches']}, ...
                    'FontName', 'Arial');
            end
        end

        function doHistF(this, visible)
            if nargin<3
                showFalsePosNeg=false;
                if nargin<2
                    visible=true;
                end
            end
            if ishandle(this.fHistFig)
                figure(this.fHistFig);
            else
                fig_=Gui.NewFigure;
                if ~visible
                    set(fig_, 'visible', 'off');
                end
                this.fHistFig=fig_;
                Gui.Resize(fig_, .66);
                Gui.Locate(fig_, this.fig, 'south east+');
                ax=axes('parent', fig_);
                [fData, avgMdn, avgMn]=this.getData(false);
                histogram(ax, fData, length(unique(fData)));

                xlabel(ax, '% overlap', 'FontName', 'Arial')
                xlim(ax, [-5 100]);
                ylabel(ax, '# of subset matches', 'FontName', 'Arial')
                set(ax, 'xlim', [0 100]);
                this.addTitleToHist(fig_, ax, ...
                    'Overlap ^{(F-measure)}', avgMdn, avgMn);
                set(ax, 'units', 'normalized', 'Position', ...
                    [.1 .16 .8 .7]);
                Gui.StretchUpper(ax, @ylim, .1);
                lbl='See false +/-';
                width=.2;
                this.addFalsePosNegButton(fig_);
                set(fig_, 'CloseRequestFcn', @(h, e)hush(h));
            end

            function hush(h)
                if ishandle(this.fig)
                    figure(this.fig);
                end
                delete(h);
            end
        end

        function addFalsePosNegButton(this, fig_, lbl, width)
            if nargin<4
                width=.2;
                if nargin<3
                    lbl='See false +/-';
                end
            end
            if isempty(this.qf.falsePosNegs)
                return;
            end
            uicontrol(fig_, 'style', 'pushbutton','String', lbl,...
                'Units', 'normalized', ...
                'FontWeight', 'bold', ...
                'ForegroundColor', 'blue',...
                'BackgroundColor', [1 1 .80],...
                'Position',[1-(width+.01), .015, width, .071],...
                'Callback', @(btn,event) browseFalsePosNeg(this));
        end

        function QF=save(this, qf, file)
            QF.tIds=qf.tIds;
            QF.sIds=qf.sIds;
            %QF.matches=qf.matches;
            %QF.getStudNames=qf.getStudNames();
            QF.tNames=qf.tNames;
            QF.tSizes=qf.tSizes;
            QF.sSizes=qf.sSizes;
            QF.matrixHtml=qf.matrixHtml;
            QF.qfTableData=this.data;
            QF.unmatched=this.unmatched;
            QF.tClrs=this.tClrs;
            QF.falsePosNegs=qf.falsePosNegs;
            qf.relocateFalsePosNegFiles(file);
            QF.falsePosNegFile=qf.falsePosNegFile;
            QF.falsePosNegSubsetsFile=qf.falsePosNegSubsetsFile;
            QF.falsePosNegCnts=qf.falsePosNegCnts;
            QF.falsePosCulprits=qf.falsePosCulprits;
            QF.falseNegCulprits=qf.falseNegCulprits;
            QF.sNames=qf.sNames;
            if nargin>2 && ~isempty(file)
                save(file, 'QF');
            end
        end

        function addSuffixToFigs(this, suffix)
            renameFig(this.fig);
            renameFig(this.qHistFig);
            renameFig(this.fHistFig);
            function renameFig(fig)
                if ~isempty(fig)
                    set(fig, 'name', [ get(fig, 'name') ' ' suffix])
                end
            end
        end

        function closeFigs(this)
            Gui.CloseFig(this.fig);
            Gui.CloseFig(this.qHistFig);
            Gui.CloseFig(this.fHistFig);
        end

        function [tUnmatched, tN, sUnmatched, sN]=getMatchCounts(this)
            [tUnmatched, tN, sUnmatched, sN]=this.qf.getMatchCounts;
        end
    end

    methods(Static)

        function QF=Load(file)
            load(file, 'QF');
        end

        function [data, names, widths, tips, unmatched, plotIdx, freqIdx,...
                rankIdx, symIdx]=Contents(qf, clrs, pu)
            unmatched=0;
            plotIdx=6;
            freqIdx=7;
            widths=[3 0; 17 nan; 5 0; 3 -2; 3 -2; ...
                    6 nan; 3 -1;  10 0; 5 nan; 8 0];
            names={'#', ...
                'Name', ...
                Html.WrapSm('Mat-
ches '), ...
                Html.WrapSm('QF dis-
similaritry'), ...
                Html.WrapSm('Overlap
F-measure'),...
                Html.WrapSm('
Trainer'), ...
                Html.WrapSm('
Freq.'), ...
                Html.WrapSm('# of
events'), ...
                '', ...
                Html.WrapSm('QF
Rank')};
            rankIdx=length(names);
            symIdx=rankIdx-1;
            tips={...
                'The subset''s item # ',...
                'The name of the subset including match name if applicable`',...
                'The number of subsets in this match set',...
                'The lower the % the more similar the match',...
                'The higher the % the more overlap (similarity) of cells (or bins)',...
                'yes for training set, no for test set ',...
                'The frequency of the subset within this selection of cells/events',...
                'The # of cells/events for the subset ',...
                'The subset''s frequency-sized symbol',...
                'The ranking of the match set'};
            try
                [data, unmatched]=qf.getTableData(clrs);
            catch ex
                if isstruct(qf)
                    data=qf.qfTableData;
                    unmatched=qf.unmatched;
                else
                    data=[];
                    unmatched=0;
                    ex.getReport
                end
            end
            if exist('pu', 'var') && ~isempty(pu)
                if ~isempty(pu.pb)
                    pu.pb.setValue(N);
                end
            end
        end

        function qft=RunWithGt(supervisors, gt, gid, fcs, fcsIdxs, ...
                data, file, embedding, visible, pu)
            qft=[];
            pFig=get(0, 'currentFig');
            if exist(file, 'file') && ~QfTable.DEBUG
                qf=QfTable.Load(file);
                qft=QfTable(qf, qf.tClrs, [], pFig, visible);
                qft.doHistQF(visible);
                if ~isempty(qft.qf.falsePosNegs)
                    qft.doHistF(visible);
                end
                return;
            end
            if isempty(fcsIdxs)
                return;
            end
            newPu=nargin<10||isempty(pu);
            if newPu
                path=BasicMap.Path;
                pu=PopUp('Generating QF dissimilarity table', 'north', ...
                    'Note...', false, true, fullfile(path, 'genieSearch.png'));
                pu.setTimeSpentTic(tic);
            else
                pu.setText2('Generating QF dissimilarity table');
            end
            [gtData, ~, ~, gtIds]=QfHiDM.GetRequiredData2(fcs, fcsIdxs, ...
                gt, gid, pu, visible);
            if isempty(gtData)
                return;
            end
            if isequal(gtData, data)
                matchStrategy=2;
            else
                matchStrategy=1;
            end
            gids=MatBasics.GetUniqueIdsAndCntIfGt0(gtIds);
            hghl=gt.highlighter;
            N=length(gids);
            gtNames=cell(1,N);
            for i=1:N
                id=num2str(gids(i));
                gtNames{i}=gt.tp.getDescription(id);
            end
            [sNames, sLbls, clrs]=supervisors.getQfTrained(embedding);

            qf=run_HiD_match(gtData, gtIds, data, sLbls, ...
                'trainingNames', gtNames, ...
                'testNames', sNames, ...
                'matchStrategy', matchStrategy, 'log10', true, 'pu', pu);
            [~,~,tIdxForS, tIdForS]=qf.getMatches;
            gtClrs=zeros(N, 3);
            for i=1:N
                clrIdx=find(tIdxForS==i, 1, 'first');
                if clrIdx>0
                    gid=tIdForS(clrIdx);
                    gtClrs(i,:)=clrs(clrIdx,:);
                else
                    gid=gids(i);
                    gtClrs(i,:)=gt.highlighter.getColor(num2str(gid));
                end
            end
            if ~isempty(qf)
                qft=QfTable(qf, gtClrs, [], pFig, visible);
                qft.doHistQF(visible);
                if matchStrategy==2
                    qft.doHistF(visible);
                end
                if ~isempty(file) && ~exist(file, 'file')
                    qft.save(qf, file);
                end
            end
            if newPu
                pu.close;
            end
        end

        function qft=Run(fcs, fcsIdxs, gt, gid1, gid2, file, visible, pu)
            pFig=get(0, 'currentFig');
            qft=[];
            if exist(file, 'file')
                qf=QfTable.Load(file);
                qft=QfTable(qf, qf.tClrs, [], pFig, visible);
                qft.doHistQF(visible);
                return;
            end
            if isempty(fcsIdxs)
                return;
            end
            newPu=nargin<8|| isempty(pu);
            if newPu
                path=BasicMap.Path;
                pu=PopUp('Generating QF dissimilarity table', 'north', ...
                    'Note...', false, true, fullfile(path, 'genieSearch.png'));
                pu.setTimeSpentTic(tic);
            else
                pu.setText2('Generating QF dissimilarity table');
            end
            [data1, ids1, names1, clrs1]=go(gid1);
            if isempty(data1)
                return;
            end
            [data2, ids2, names2, clrs2]=go(gid2);
            if isempty(data2)
                return;
            end
            matchStrategy=1;
            qf=run_HiD_match(data1, ids1, data2, ids2, ...
                'trainingNames', names1, 'testNames', names2, ...
                'matchStrategy', matchStrategy, 'log10', true, ...
                'pu', pu);
            if ~isempty(qf)
                qft=QfTable(qf, clrs1, [], pFig, visible);
                qft.doHistQF(visible);
                if ~isempty(file) && ~exist(file, 'file')
                    qft.save(qf, file);
                end
            end
            if newPu
                pu.close;
            end

            function [gtData, gtIds, names, clrs]=go(gid)
                [gtData, ~, ~, gtIds]=QfHiDM.GetRequiredData2(fcs, ...
                    fcsIdxs, gt, gid, pu, visible);
                if isempty(gtData)
                    return;
                end
                gids=MatBasics.GetUniqueIdsAndCntIfGt0(gtIds);
                hghl=gt.highlighter;
                N=length(gids);
                clrs=zeros(N, 3);
                names=cell(1,N);
                for i=1:N
                    id=num2str(gids(i));
                    names{i}=gt.tp.getDescription(id);
                    clrs(i,:)=hghl.getColor(id, Gui.HslColor(i, N));
                end
            end
        end
    end
end

author: canlab

repo: CanlabCore

save_path: github-repos/MATLAB/canlab-CanlabCore


text:
function val=superfactorial(n)
%%SUPERFACTORIAL Evaluate the superfactorial of a nonnegative real integer.
%                This is factorial(1)*factorial(2)*...factorial(n).
%
%INPUTS: n A scalar or matrix of real integers >=0.
%
%OUTPUTS: val A matrix having the same dimensions as n holding the
%             superfactorial of the values in n.
%
%The superfactorial is defined in [1]. For values 18 and below, the value
%is taken from a tabel. For higher values, the value is computed from the
%definition starting from the value at 18, maintaining the current
%factorial value at each step. Values 27 and higher overflow with double
%precision arithmetic.
%
%REFERENCES:
%[1] Weisstein, Eric W. "Superfactorial." From MathWorld--A Wolfram Web
%    Resource. http://mathworld.wolfram.com/Superfactorial.html
%
%September 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

%A table of values for 0<=n<=18
valTable=[1;
          1;
          2;
          12;
          288;
          34560;
          24883200;
          125411328000;
          5056584744960000;
          1834933472251084800000;
          6658606584104736522240000000;
          265790267296391946810949632000000000;
          127313963299399416749559771247411200000000000;
          792786697595796795607377086400871488552960000000000000;
          69113789582492712943486800506462734562847413501952000000000000000;
          90378331112371142262979521568630736335023247731599748366336000000000000000000;
          1890966832292234727042877370627225068196418587883634153182519380410368000000000000000000000;
          672593129192865130334217631473916658864122332882577979675277211683839238972899328000000000000000000000000;
          4306192564997715382115598640379294845786123319603755168023536027873932927153136831171640950784000000000000000000000000000];

if(any(n(:)<0)||any(n(:)~=fix(n(:)))||any(~isreal(n(:))))
    error('n must be a positive integer.')
end
val=zeros(size(n));

numVals=numel(n);

for curEl=1:numVals
    nCur=n(curEl);

    if(nCur<=18)
        val(curEl)=valTable(nCur+1);
    else
        factVal=6402373705728000;%factorial(18)
        val(curEl)=valTable(18+1);

        for curN=19:nCur
            %Quit if there was an overflow.
            if(~isfinite(val(curEl)))
                break;
            end
            factVal=factVal*curN;
            val(curEl)=val(curEl)*factVal;
        end
    end
end
end

%LICENSE:
%
%The source code is in the public domain and not licensed or under
%copyright. The information and software may be used freely by the public.
%As required by 17 U.S.C. 403, third parties producing copyrighted works
%consisting predominantly of the material produced by U.S. government
%agencies must provide notice with such work(s) identifying the U.S.
%Government material incorporated and stating that such material is not
%subject to copyright protection.
%
%Derived works shall not identify themselves in a manner that implies an
%endorsement by or an affiliation with the Naval Research Laboratory.
%
%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE
%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL
%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS
%OF RECIPIENT IN THE USE OF THE SOFTWARE.

author: USNavalResearchLaboratory

repo: TrackerComponentLibrary


text:
pointcolor=[rand rand rand];
figure
for count=1:size(AGS,2)
    plot(count,AGS(1,count),'o','MarkerSize',2.5,'MarkerEdgeColor',[pointcolor(1,1) pointcolor(1,2) pointcolor(1,3)],...
        'MarkerFaceColor',[pointcolor(1,1) pointcolor(1,2) pointcolor(1,3)]);axis square;box on;grid on;hold on
end
title('Average Grain Size Vs. MCS')
xlabel('Monte - Carlo Steps')
ylabel('Unit Normalized Average Grain Size')
pause(0.5)

author: Sable

repo: mcbench-benchmarks

path: github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/34784-monte-carlo-simulation-of-two-dimensional-grain-growth-code-version-no-1-basic/Monte Carlo Simulation Q-state Potts model 2D square-lattice - microstructure/PlotAverageGrainSize_2D_QPOTTS.m


text:
function pred = FDDL_pred_LC(Y, D, CoefM, opts) % LC
%     vgamma = opts.gamma;
    gamma1 = opts.gamma1;
    gamma2 = opts.gamma2;
    C = size(CoefM, 2);
    E = zeros(C, size(Y, 2));
    for c = 1: C
        Dc = get_block_col(D, c, opts.D_range);
        mii = get_block_row(CoefM(:, c), c, opts.D_range);
        [~, min_cost] = sparse_coding(Y, Dc, [], mii, gamma1, gamma2);
        E(c, :)  = min_cost;
    end
    [~, pred] = min(E);
    % opts.max_iter = 100;
    % [X, ~] = lasso_fista(Y, D, zeros(size(D,2), size(Y,2)), vgamma, opts);
    % C = size(CoefM,2);
    % % w = 0.5;
    % E = zeros(C, size(Y,2));
    % for c = 1: C
    %     Dc = get_block_col(D, c, opts.D_range);
    %     Xc = get_block_row(X, c, opts.D_range);
    %     R1 = Y - Dc*Xc;
    %     E1 = sum(R1.^2);
    %     R2 = X - repmat(CoefM(:, c), 1, size(Y,2));
    %     E2 = sum(R2.^2);
    %     E(c,:) = E1 + opts.weight*E2;
    % end
    % [~, pred] = min(E);

    % sparse_coding();
end

function [X, min_cost] = sparse_coding(Y, D, Xinit, m, gamma1, gamma2)
% function X = sparse_coding(Y, D, Xinit, m, gamma1, gamma2)
% Solve the problem:
% X = argmin_X .5*||Y - DX|| + gamma1*||X|| + 0.5*gamma2* ||X - M||_F^2
% gradient: D'(DX - Y) + gamm2*(X - M) = (D'D + gamma2*I)*X - D'Y - gamma2*M;
% -----------------------------------------------
% Author: Tiep Vu, thv102@psu.edu, 5/23/2016 11:00:18 AM
%         (http://www.personal.psu.edu/thv102/)
% -----------------------------------------------
    if nargin == 0 %% test mode
        d = 10;
        N = 20;
        k = 10;
        Y = normc(rand(d, N));
        D = normc(rand(d, k));
        Xinit = [];
        m = rand(k, 1);
        gamma1 = 0.001;
        gamma2 = 0.01;
    end
    %%
    if numel(Xinit) == 0
        Xinit = zeros(size(D, 2), size(Y, 2));
    end
    M = repmat(m, 1, size(Y, 2));
    %% cost
    function cost = calc_f(X)
        cost = 0.5*normF2(Y - D*X) + 0.5*gamma2*normF2(X - M);
    end
    %% cost overall
    function cost = calc_F(X)
        cost = calc_f(X) + gamma1*norm1(X);
    end
    %% gradient
    A = D'*D + gamma2*eye(size(D, 2));
    B = D'*Y + gamma2*M;
    function g = grad(X)
        g = A*X - B;
    end
    %% check_grad
    %  check_grad(@calc_f, @grad, Xinit);
    %% L
    L = max(eig(A));
    %% opts
    opts.max_iter = 300;
    opts.verbose = 0;
    [X, ~] = fista(@grad, Xinit, L, gamma1, opts, @calc_F);
    %% min_cost for each sample (column)
    min_cost = zeros(1, size(Y, 2));
    R1 = Y - D*X;
    R2 = X - M;
    min_cost = sum(R1.^2, 1) + gamma1*sum(abs(X), 1) + ...
                gamma2*sum(R2.^2, 1);
end

author: tiepvupsu

repo: DICTOL

save_path: github-repos/MATLAB/tiepvupsu-DICTOL


text:
function [varargout]=mat2wfdb(varargin)
%
% [xbit]=mat2wfdb(X,fname,Fs,bit_res,adu,info,gain,sg_name,baseline,isquant, isdigital)
%
% Convert data from a matlab array into Physionet WFDB format file.
%
% Input Paramater are:
%
% X       -(required)  NxM matrix of M signals with N samples each. The
%                      signals can be of type double.The signals are assumed to be
%                      in physical units already and will be converted to
%                      ADU.
% fname   -(required)  String where the the header (*.hea) and data (*.dat)
%          files will be saved (one single name for both, with no sufix).
% Fs      -(Optional)  1x1 sampling frequency in Hz (all signals must have
%          been sampled at the same frquency). Default is 1 Hz.
% bit_res -(Optional)  1xM (or Mx1):scalar determining the bit depth of the conversion for
%                      each signal.
%                      1x1 : If all the signals should have the same bit depth
%          Options are: 8,  16, and 32 ( all are signed types). 16 is the default.
% adu     -(Optional) Describes the physical units (default is 'mV').
%          Three input formats:
%            - String delimited by forward slashes (e.g. 'V/mV/mmHg'), with
%            M-1 slash characters
%            - Single string (e.g. 'V'), in which case all signals will
%            have the same physical units.
%            - Cell array of strings, where the total units entered has to equal M
%            (number of channels).
% info    -(Optional)  String that will be added to the comment section of the header file.
%           For multi-lined comments, use a cell array of strings. Each
%           cell will be output on a new line. Note that comments in the
%           header file are automatically prefixed with a pound symbol (#)
% gain    -(Required for digital only) Scalar or Mx1 array of floats indicating the difference in sample values
%           that would be observed if a step of one physical unit occurred in the original
%           analog signal. If the 'isdigital' field is 1, this field is mandatory. Otherwise,
%           this field is ignored if present.
% baseline -(Required for digital only) Mx1 array of integers that specifies the sample value for each channel
%           corresponding to 0 physical units. Not to be confused with 'ADC zero' which
%           is currently always taken and written as 0 in this function. If
%           the 'isdigital' field is 1, this field is mandatory. Otherwise,
%           this field is ignored if present.
% sg_name -(Optional) Cell array of strings describing signal names.
%
% isquant   -(Optional) Logical value (default=0). Use this option if the
%           input signal is already quantitized and you want to remove round-off
%           error by mapping the original values to integers prior to fixed
%           point conversion. This field is only used for input physical
%           signals. If 'isdigital' is set to 1, this field is ignored.
%
% isdigital -(Optional) Logical value (default=0). Specifies whether the input signal is
%            digital or physical (default). If it is digital, the signal values will be
%            directly written to the file without scaling. If the signal is physical,
%            the optimal gain and baseline will be calculated and used to digitize the signal
%            to write the WFDB file. This flag also decides the allowed
%            input combinations of the 'gain' and 'baseline' fields.
%            Digital signals must have both, and physical signals must have
%            neither (as the ideal values will be automatically calculated).
%
% Ouput Parameter:
%
% xbit    -(Optional)  NxM the quantitized signals that written to file (possible
%          rescaled if no gain was provided at input). Useful for comparing
%          and estimating quatitization error with the input double signal X
%          (see examples below).
%
%
%  NOTE: The signals can have different amplitudes, they will all be scaled to
%  a reference gain, with the scaling factor saved in the *.hea file.
%
%Written by Ikaro Silva 2010
%Modified by Louis Mayaud 2011, Alistair Johson 2016
% Version 1.0
%
% Since 0.0.1
% See also wrsamp, wfdbdesc
%
%%%%%%%%%%  Example 1 %%%%%%%%%%%%
%
% display('***This example will write a  Ex1.dat and Ex1.hea file to your current directory!')
% s=input('Hit "ctrl + c" to quit or "Enter" to continue!');
%
% %Generate 3 different signals and convert them to signed 16 bit in WFDB format
% clear all;clc;close all
% N=1024;
% Fs=48000;
% tm=[0:1/Fs:(N-1)/Fs]';
% adu='V/mV/V';
% info='Example 1';
%
%
% %First signal a ramp with 2^16 unique levels and is set to (+-) 2^15 (Volts)
% %Thus the header file should have one quant step equal to (2^15-(-2^15))/(2^16) V.
% sig1=double(int16(linspace(-2^15,2^15,N)'));
%
% %Second signal is a sine wave with 2^8 unique levels and set to (+-) 1 (mV)
% %Thus the header file should one quant step equal a (1--1)/(2^8)  adu step
% sig2=double(int8(sin(2*pi*tm*1000).*(2^7)))./(2^7);
%
% %Third signal is a random binary signal set to to (+-) 1 (V) with DC (to be discarded)
% %Thus the header file should have one quant step equal a 1/(2^15) adu step.
% sig3=(rand(N,1) > 0.97)*2 -1 + 2^16;
%
% %Concatenate all signals and convert to WFDB format with default 16 bits (empty brackets)
% sig=[sig1 sig2 sig3];
% mat2wfdb(sig,'Ex1',Fs,[],adu,info)
%
% % %NOTE: If you have WFDB installed you can check the conversion by
% % %uncomenting and this section and running (notice that all signals are scaled
% % %to unit amplitude during conversion, with the header files keeping the gain info):
%
% % !rdsamp -r Ex1 > foo
% % x=dlmread('foo');
% % subplot(211)
% % plot(sig)
% % subplot(212)
% % plot(x(:,1),x(:,2));hold on;plot(x(:,1),x(:,3),'k');plot(x(:,1),x(:,4),'r')
%
%%%%%%%% End of Example 1%%%%%%%%%

%endOfHelp
machine_format='l'; % all wfdb formats are little endian except fmt 61 which this function does not support. Do NOT change this.
skip=0;

% Set default parameters
params={'x','fname','Fs','bit_res','adu','info','gain','sg_name','baseline','isquant', 'isdigital'};
Fs=1;
adu=[];
info=[];
isquant=0;
isdigital=0;
%Use cell array for baseline and gain in case of empty conditions
baseline=[];
gain=[];
sg_name=[];
x=[];
fname=[];
%Used to convert signal from double to appropiate type
bit_res = 16 ;
bit_res_suport=[8 16 32];

for i=1:nargin
    if(~isempty(varargin{i}))
        eval([params{i} '= varargin{i};']);
    end
end

disp(isdigital);
% Check valid gain and baseline combinations depending on whether the input is digital or physical.
if isdigital % digital input signal
    if (isempty(gain) || isempty(baseline))
        error('Input digital signals are directly written to files without scaling. Must also input gain and baseline for correct interpretation of written file.');
    end
    if (~isempty(find(baseline>2147483647))||~isempty(find(baseline<-2147483648))) % baseline stored as int in wfdb library.
        error('Baseline field must lie between 2^-31 and 2^31-1 for this WFDB version'); % Prevent bit overflow
    end
else % physical input signal
    if ( ~isempty(gain) || ~isempty(baseline)) % User inputs gain or baseline to map the physical to digital values.
        % Sorry, we cannot trust that they did it correctly...
        warning('Input gain and baseline fields ignored for physical input signal. This function automatically calculates and applies the ideal values');
    end
end

switch bit_res % Write formats.
    case 8
        fmt='80';
    case 16
        fmt='16';
    case 32
        fmt='32';
end

[N,M]=size(x);

if isempty(adu) % default unit: 'mV'
    adu=repmat({'mV'},[M 1]);
elseif iscell(adu)
    % adu directly input as a cell array of strings
elseif ischar(adu)
    if ~isempty(strfind(adu,'/'))
        adu=regexp(adu,'/','split');
    else
        adu = repmat({adu},[M,1]);
    end
end

% ensure we have the right number of units
if numel(adu) ~= M
    error('adu:wrongNumberOfElements','adu cell array has incorrect number of elements');
end

if(isempty(gain))
    gain=cell(M,1); %Generate empty cells as default
elseif(length(gain)==1)
    gain=repmat(gain,[M 1]);
end
% ensure gain is a cell array
if isnumeric(gain)
    gain=num2cell(gain);
end

if(isempty(sg_name))
    sg_name=repmat({''},[M 1]);
end
if ~isempty(setdiff(bit_res,bit_res_suport))
    error(['Bit res should be one of: ' num2str(bit_res_suport)]);
end
if(isempty(baseline))
    baseline=cell(M,1); %Generate empty cells as default
elseif(length(baseline)==1)
    baseline=repmat(baseline,[M 1]);
end
% ensure baseline is a cell array
if isnumeric(baseline)
    baseline=num2cell(baseline);
end

if isempty(isquant)
    isquant = zeros(M,1);
elseif numel(isquant)==1
    isquant = repmat(isquant,[M,1]);
elseif numel(isquant)~=M
    error('isquant:wrongNumberOfElements','isquant  array has incorrect number of elements');
end

%Head record specification line
head_str=cell(M+1,1);
head_str(1)={[fname ' ' num2str(M) ' ' num2str(Fs) ' ' num2str(N)]};

switch bit_res % Allocate space for digital signals
    case 8
        y=uint8(zeros(N,M));
    case 16
        y=int16(zeros(N,M));
    case 32
        y=int32(zeros(N,M));
end

%Loop through all signals, digitizing them and generating lines in header file
for m=1:M
    nameArray = regexp(fname,'/','split');
    if ~isempty(nameArray)
        fname = nameArray{end};
    end

    [tmp_bit1,bit_gain,baseline_tmp,ck_sum]=quant(x(:,m), ...
        bit_res, gain{m}, baseline{m}, isquant(m), isdigital);

    y(:,m)=tmp_bit1;

    % Header file signal specification lines
    % Should we specify precision of num2str(gain)?
    head_str(m+1)={[fname '.dat ' fmt ' ' num2str(bit_gain) '(' ...
        num2str(baseline_tmp) ')/' adu{m} ' ' num2str(bit_res) ' 0 ' num2str(tmp_bit1(1)) ' ' num2str(ck_sum) ' 0 ' sg_name{m}]};
end
if(length(y)<1)
    error(['Converted data is empty. Exiting without saving file...']);
end

%Write *.dat file
fid = fopen([fname '.dat'],'wb',machine_format);
if(~fid)
    error(['Could not create data file for writing: ' fname]);
end

if (bit_res==8)
    count=fwrite(fid, y','uint8',skip,machine_format);
else
    count=fwrite(fid, y',['int' num2str(bit_res)],skip,machine_format);
end

if(~count)
    fclose(fid);
    error(['Could not data write to file: ' fname]);
end

fprintf(['Generated *.dat file: ' fname '\n']);
fclose(fid);

%Write *.hea file
fid = fopen([fname '.hea'],'w');
for m=1:M+1
    if(~fid)
        error(['Could not create header file for writing: ' fname]);
    end
    fprintf(fid,'%s\n',head_str{m});
end

if(~isempty(info))
    if ischar(info)
        fprintf(fid,'#%s\n',info);
    elseif iscell(info)
        for m=1:numel(info)
            fprintf(fid,'#%s\n',info{m});
        end
    end
end

if(nargout==1)
    varargout(1)={y};
end
fprintf(['Generated *.hea file: ' fname '\n']);
fclose(fid);

end

%%%End of Main %%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%Helper function
function [y,adc_gain,baseline,check_sum]=quant(x, bit_res, gain, baseline, isquant, isdigital)

min_x=min(x(~isnan(x)));
max_x=max(x(~isnan(x)));
nan_ind=isnan(x);
rg=max_x-min_x;

if(isdigital)
    % Digital input signal. Do not scale or shift the signal. The gain/baseline will only
    % be used to write the header file to interpret the output wfdb record.
    if ((min_x < -2^(bit_res-1)+1) || (max_x > (2^(bit_res-1)-1 )))
        error(['Digital input signal exceeds allowed range of specified output format: {' num2str(-2^(bit_res-1)+1) ' < x < ' num2str(2^(bit_res-1)-1) '}']);
    end
    adc_gain=gain;
    y=x;

else
    % Physical input signal - calculate the gain and baseline to minimize
    % the detail loss during ADC conversion: y = gain*x + baseline. Ignore any input gain or baseline

    % Calculate the adc_gain, baseline, and map the signal to digital
    % Make sure baseline doesn't go beyond 4 byte integer range

    if rg==0 % Flatline signal. Manually set adc_gain or it will be infinite.
          baseline=-(2^(bit_res-1))+1; % Set baseline to minimum value of bit res
          if x(1)==0
            adc_gain=1; % Arbitrary gain=1 for all 0 input signal. All values stored as baseline.
          else
            adc_gain=-baseline/x(1); % Set gain as inverse to store all values as exactly 0.
          end

    else % Non flatline signal: adc_gain = (range of encoding / range of Data) -- remember 1 quant level is for storing NaN
        % Constraint - baseline must be stored as a 4 byte integer for the WFDB library.
        if ((min_x>0) && (bit_res==32)) % All values are +ve, map with baseline = -2^31+1
            adc_gain=((2^32)-2)/max_x;
            baseline=-2147483647;
            if isquant==0 % Only display warning message if not recalculating later
                disp('Due to baseline constraints, output precision may be slightly less than 32 bits for the positive channel.');
            end
        elseif((max_x<0) && (bit_res==32)) % All values are -ve, map with baseline = 2^31-1
            adc_gain=((2^32)-2)/abs(min_x);
            baseline=2147483647;
            if isquant==0 % Only display warning message if not recalculating later
                disp('Due to baseline constraints, output precision may be slightly less than 32 bits for the negative channel.');
            end
        else % Signal has both +ve and -ve values or fmt is not 32. Use full range of bits.
            adc_gain=((2^bit_res)-2)/rg;
            baseline=round(-(2^(bit_res-1))+1-min_x*adc_gain);

        end
        if(isquant)
            % The (non flatline) input signal was already quantitized. Remove round-off error
            % by setting the original values to integers prior to fixed point conversion

            xvalues=sort(unique(x(~isnan(x)))); % All the values of x
            incmin=min(diff(xvalues)); % An estimate of the smallest possible increment in the input signal
            quantlevels=rg/incmin; % The estimated number of quantization levels in the input signal

            % We want to map 1 increment to 1 digital unit. First make sure
            % the full increment range is less than the 2^N-2 increments able to be encoded
            % by the chosen bit resolution. The incmin estimate will always
            % be equal to or larger than the true incmin, so it won't
            % wrongly trigger errors in this validation step.

            if (quantlevels>2^bit_res-2)
                if bit_res==32
                    disp(['The input signal has more quantization levels than 32 bits -1. ' ...
                        'Cannot directly map all input values to integers. Up to 1 bit of roundoff error may occur. Continuing...']);
                    calcquant=0; % Skip the integer matching and keep the old baseline/gain calculated.
                else
                    error(['The input signal has more quantization levels than the chosen bit resolution. ' ...
                        'Please choose a higher resolution or remove the isquant option to allow up to 1 bit of roundoff error']);
                end
            else
                calcquant=1;
            end

            % Calculate gain+offset. Baseline must be stored as a 4 byte integer for the WFDB library.
            if calcquant
                if ((min_x>0) && (bit_res==32)) % 32 bit +ve quant mapping
                    adc_gain=1/incmin;
                    baseline=round(2147483647-adc_gain*max_x); % map max_x to 2^31-1.
                    if (baseline<-2147483647) % Check if baseline goes below -2^31-1. If so, no quant. Recalculate gain and base.
                        adc_gain=((2^32)-2)/max_x;
                        baseline=-2147483647;
                        disp('Due to baseline constraints, the channel will not be quantized. Output precision may be less than 32 bits for the positive channel.');
                    end
                elseif((max_x<0) && (bit_res==32)) % 32 bit -ve quant mapping
                    adc_gain=1/incmin;
                    baseline=round(-2147483647-adc_gain*min_x); % map min_x to -2^31+1.
                    if (baseline>2147483647) % Check if baseline goes above 2^31-1. If so, no quant. Recalculate gain and base.
                        adc_gain=((2^32)-2)/abs(min_x);
                        baseline=2147483647;
                        disp('Due to baseline constraints, channel will not be quantized. Output precision may be less than 32 bits for the negative channel.');
                    end
                else % Signal has both +ve and -ve values or fmt is not 32. Can use full range of bits.
                    adc_gain=1/incmin; % 1 digital unit corresponds to the smallest physical increment.
                    baseline=round(-(2^(bit_res-1))+1-min_x*adc_gain); % xmin still maps to ymin. xmax will not go beyond y limit, baseline should not go beyond 32 bit limits.
                end
            end
        end
        % Check for 8 and 16 bit format 'baseline' field overflow. VERY
        % uncommon situation. Occurs if entire signal is +ve or -ve
        % with very high magnitude.
        if (baseline>2147483647) % Signal is all negative with large magnitude.
            warning('Large offset input channel entered. Output precision may be less than specified format for the negative channel.');
            baseline=2147483647; % Baseline is max int value, min_x maps to min bitres value.
            adc_gain=(-(2^(bit_res-1))+1-baseline)/min_x;
        elseif (baseline<-2147483647) % Signal is all positive with large magnitude.
            warning('Large offset input channel entered. Output precision may be less than specified format for the positive channel.');
            baseline=-2147483647; % Baseline is min int value, max_x maps to max bitres value.
            adc_gain=(2^(bit_res-1)-1-baseline)/max_x;
        end
    end

    y=x*adc_gain+baseline;

end % signal is in digital range. adc_gain and baseline have been calculated.

% Convert signals to appropriate integer type, and shift any WFDB NaN int values to
% a higher value so that they will not be read as NaN's by WFDB
switch bit_res % WFDB will interpret the smallest value as nan.
    case 8
        WFDBNAN=-128;
        y=int8(y);
    case 16
        WFDBNAN=-32768;
        y=int16(y);
    case 32
        WFDBNAN=-2147483648;
        y=int32(y);
end
iswfdbnan=find(y==WFDBNAN);
if(~isempty(iswfdbnan))
    y(iswfdbnan)=WFDBNAN+1;
end

%Set original NaNs to WFDBNAN
y(nan_ind)=WFDBNAN;

%Calculate the 16-bit signed checksum of all samples in the signal
check_sum=sum(y);
M=check_sum/(2^15);
if(M<0)
    check_sum=mod(check_sum,-2^15);
    if(~check_sum && abs(M)<1)
        check_sum=-2^15;
    elseif (mod(ceil(M),2))
        check_sum=2^15 + check_sum;
    end
else
    check_sum=mod(check_sum,2^15);
    if(mod(floor(M),2))
        check_sum=-2^15+check_sum;
    end
end

% Note that checksum must be calculated on actual digital samples for format 80,
% not the shifted ones. Therefore we only convert to real format now.
if bit_res==8
    y=uint8(int16(y)+128); % Convert into unsigned for writing byte offset format.
end

% Signal is ready to be written to dat file.

end

function y=get_names(str,deli)

y={};
old=1;
ind=regexp(str,deli);
ind(end+1)=length(str)+1;
for i=1:length(ind)
    y(end+1)={str(old:ind(i)-1)};
    old=ind(i)+1;
end

end

author: ikarosilva

repo: wfdb-app-toolbox


text:
%DEMGMM5 Demonstrate density modelling with a PPCA mixture model.
%
%	Description
%	 The problem consists of modelling data generated by a mixture of
%	three Gaussians in 2 dimensions with a mixture model using full
%	covariance matrices.  The priors are 0.3, 0.5 and 0.2; the centres
%	are (2, 3.5), (0, 0) and (0,2); the variances are (0.16, 0.64) axis
%	aligned, (0.25, 1) rotated by 30 degrees and the identity matrix. The
%	first figure contains a scatter plot of the data.
%
%	A mixture model with three one-dimensional PPCA components is trained
%	using EM.  The parameter vector is printed before training and after
%	training.  The parameter vector consists of priors (the column), and
%	centres (given as (x, y) pairs as the next two columns).
%
%	The second figure is a 3 dimensional view of the density function,
%	while the third shows the axes of the 1-standard deviation ellipses
%	for the three components of the mixture model together with the one
%	standard deviation along the principal component of each mixture
%	model component.
%
%	See also
%	GMM, GMMINIT, GMMEM, GMMPROB, PPCA
%

%	Copyright (c) Ian T Nabney (1996-2001)

ndata = 500;
data = randn(ndata, 2);
prior = [0.3 0.5 0.2];
% Mixture model swaps clusters 1 and 3
datap = [0.2 0.5 0.3];
datac = [0 2; 0 0; 2 3.5];
datacov = repmat(eye(2), [1 1 3]);
data1 = data(1:prior(1)*ndata,:);
data2 = data(prior(1)*ndata+1:(prior(2)+prior(1))*ndata, :);
data3 = data((prior(1)+prior(2))*ndata +1:ndata, :);

% First cluster has axis aligned variance and centre (2, 3.5)
data1(:, 1) = data1(:, 1)*0.1 + 2.0;
data1(:, 2) = data1(:, 2)*0.8 + 3.5;
datacov(:, :, 3) = [0.1*0.1 0; 0 0.8*0.8];

% Second cluster has variance axes rotated by 30 degrees and centre (0, 0)
rotn = [cos(pi/6) -sin(pi/6); sin(pi/6) cos(pi/6)];
data2(:,1) = data2(:, 1)*0.2;
data2 = data2*rotn;
datacov(:, :, 2) = rotn' * [0.04 0; 0 1] * rotn;

% Third cluster is at (0,2)
data3(:, 2) = data3(:, 2)*0.1;
data3 = data3 + repmat([0 2], prior(3)*ndata, 1);

% Put the dataset together again
data = [data1; data2; data3];

ndata = 100;			% Number of data points.
noise = 0.2;			% Standard deviation of noise distribution.
x = [0:1/(2*(ndata - 1)):0.5]';
randn('state', 1);
rand('state', 1);
t = sin(2*pi*x) + noise*randn(ndata, 1);

% Fit three one-dimensional PPCA models
ncentres = 3;
ppca_dim = 1;

clc
disp('This demonstration illustrates the use of a Gaussian mixture model')
disp('with a probabilistic PCA covariance structure to approximate the')
disp('unconditional probability density of data in a two-dimensional space.')
disp('We begin by generating the data from a mixture of three Gaussians and')
disp('plotting it.')
disp(' ')
disp('The first cluster has axis aligned variance and centre (0, 2).')
disp('The variance parallel to the x-axis is significantly greater')
disp('than that parallel to the y-axis.')
disp('The second cluster has variance axes rotated by 30 degrees')
disp('and centre (0, 0).  The third cluster has significant variance')
disp('parallel to the y-axis and centre (2, 3.5).')
disp(' ')
disp('Press any key to continue.')
pause

fh1 = figure;
plot(data(:, 1), data(:, 2), 'o')
set(gca, 'Box', 'on')
axis equal
hold on

mix = gmm(2, ncentres, 'ppca', ppca_dim);
options = foptions;
options(14) = 10;
options(1) = -1;  % Switch off all warnings

% Just use 10 iterations of k-means in initialisation
% Initialise the model parameters from the data
mix = gmminit(mix, data, options);
disp('The mixture model has three components with 1-dimensional')
disp('PPCA subspaces.  The model parameters after initialisation using')
disp('the k-means algorithm are as follows')
disp('    Priors        Centres')
disp([mix.priors' mix.centres])
disp(' ')
disp('Press any key to continue')
pause

options(1)  = 1;		% Prints out error values.
options(14) = 30;		% Number of iterations.

disp('We now train the model using the EM algorithm for up to 30 iterations.')
disp(' ')
disp('Press any key to continue.')
pause

[mix, options, errlog] = gmmem(mix, data, options);
disp('The trained model has priors and centres:')
disp('    Priors        Centres')
disp([mix.priors' mix.centres])

% Now plot the result
for i = 1:ncentres
  % Plot the PC vectors
  v = mix.U(:,:,i);
  start=mix.centres(i,:)-sqrt(mix.lambda(i))*(v');
  endpt=mix.centres(i,:)+sqrt(mix.lambda(i))*(v');
  linex = [start(1) endpt(1)];
  liney = [start(2) endpt(2)];
  line(linex, liney, 'Color', 'k', 'LineWidth', 3)
  % Plot ellipses of one standard deviation
  theta = 0:0.02:2*pi;
  x = sqrt(mix.lambda(i))*cos(theta);
  y = sqrt(mix.covars(i))*sin(theta);
  % Rotate ellipse axes
  rot_matrix = [v(1) -v(2); v(2) v(1)];
  ellipse = (rot_matrix*([x; y]))';
  % Adjust centre
  ellipse = ellipse + ones(length(theta), 1)*mix.centres(i,:);
  plot(ellipse(:,1), ellipse(:,2), 'r-')
end

disp(' ')
disp('Press any key to exit')
pause
close (fh1);
clear all;

author: bayesnet

repo: bnt

save_path: github-repos/MATLAB/bayesnet-bnt


text:
function LR_chi2=drxlr_get_lrt(y,mu)
% compute the likelihood ratio test
% written by Issam El Naqa
%
% Copyright 2010, Joseph O. Deasy, on behalf of the DREES development team.
%
% This file is part of the Dose Response Explorer System (DREES).
%
% DREES development has been led by:  Issam El Naqa, Aditya Apte, Gita Suneja, and Joseph O. Deasy.
%
% DREES has been financially supported by the US National Institutes of Health under multiple grants.
%
% DREES is distributed under the terms of the Lesser GNU Public License.
%
%     This version of DREES is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
% DREES is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
% See the GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with DREES.  If not, see <http://www.gnu.org/licenses/>.

seps = sqrt(eps);
n=length(y);
n1=sum(y); n0=sum(1-y);
Ls=n1*log(n1)+n0*log(n0)-n*log(n); % saturated
L=sum(y.*log(mu+seps)+(1-y).*log(1-mu+seps)); % fitted
LR_chi2=2*(L-Ls); % follows centered chi2 stats
return

author: mvallieres

repo: radiomics