I have what appears to be functioning ASP code but it is returning no answer set? - answer-set-programming

I am attempting to solve a Binary sudoku puzzle with Answer Set Programming, Clingo, and MKAtoms. I have a working set of code, but it is not returning any answer sets.
I have reviewed the code but am unsure of the problem.
% Binary Sudoku solver: Binary Sudoku is a similar puzzle to sudoku.
% The rules are as follows
% 1. Each row and column must have the same number of 1's and 0's
% 2. Each row and column must be unique
% 3. Each number may not appear in consecutive triples
%
% The program works in conjuction with python 3.6, Clingo, and Mkatoms to create the required files and solve the user input puzzle.
%
% Required Files:
% BinaryTemp.sm
% BinaryOut.sm
% BinaryPy.sm - This File
%
% Using the defined rules Clingo will attempt to find an answer set that will statisfy all conditions
num(0..1).
range(0..6).
% There may only be one number in each X,Y position
1{pos(N,X,Y):num(N)}1 :- num(X), num(Y).
% Each row and column must have the same number of 1’s and 0’s
% Row check - check each rows sum to see if they hold the same number of 1's
total_row(S) :- S = #sum{ N : pos(N,X,Y1), pos(N,X+1,Y1), pos(N,X+2,Y1), pos(N,X+3,Y1), pos(N,X+4,Y1), pos(N,X+5,Y1)}.
total_row1(S) :- S = #sum{ N : pos(N,X,Y2), pos(N,X+1,Y2), pos(N,X+2,Y2), pos(N,X+3,Y2), pos(N,X+4,Y2), pos(N,X+5,Y2)}.
:- total_row(S) != total_row1(S), range(S).
% Column Check
total_column(S) :- S = #sum{ N : pos(N,X1,Y), pos(N,X,Y+1), pos(N,X1,Y+2), pos(N,X1,Y+3), pos(N,X1,Y+4), pos(N,X1,Y+5)}.
total_column1(S) :- S = #sum{ N : pos(N,X2,Y), pos(N,X2,Y+1), pos(N,X2,Y+2), pos(N,X2,Y+3), pos(N,X2,Y+4), pos(N,X2,Y+5)}.
:- total_column(S) != total_column1(S), range(S).
% Each row and column must be unique
% Row check - check if 2 values in seperate rows are different
different(X1,X2) :- pos(N1,X1,Y), pos(N2,X2,Y), N1!=N2.
:-pos(N,X1,Y), pos(N,X2,Y), X1!=X2, not different(X1,X2).
% Column check
different(Y1,Y2) :- pos(N1,X,Y1), pos(N2,X,Y2), N1!=N2.
:-pos(N,X,Y1), pos(N,X,Y2), Y1!=Y2, not different(Y1,Y2).
% Each number may not appear in consecutive triples
:-pos(N,X,Y), pos(N,X+1,Y), pos(N,X+2,Y), num(N).
:-pos(N,X,Y), pos(N,X,Y+2), pos(N,X,Y+2), num(N).
#show pos/3.
Input File:
- pos(0,1,1).
- pos(1,1,4).
- pos(1,2,2).
- pos(0,2,5).
- pos(1,3,6).
- pos(1,4,3).
- pos(0,4,4).
- pos(1,5,1).
- pos(0,5,4).
- pos(0,6,2).
- pos(1,6,5).
There are no errors but it should return positions of answers matching the rules stated above.

Related

Passing parameters to a Matlab function

I have a very simple question, but I didn't figure out how to solve this.I have the function definition below:
function model = oasis(data, class_labels, parms)
% model = oasis(data, class_labels, parms)
%
% Code version 1.3 May 2011 Fixed random seed setting
% Code version 1.2 May 2011 added call to oasis_m.m
% Code version 1.1 May 2011 handle gaps in class_labels
%
% Input:
% -- data - Nxd sparse matrix (each instance being a ROW)
% -- class_labels - label of each data point (Nx1 integer vector)
% -- parms (do sym, do_psd, aggress etc.)
%
% Output:
% -- model.W - dxd matrix
% -- model.loss_steps - a binary vector: was there an update at
% each iterations
% -- modeo.parms, the actual parameters used in the run (inc. defaults)
%
% Parameters:
% -- aggress: The cutoff point on the size of the correction
% (default 0.1)
% -- rseed: The random seed for data point selection
% (default 1)
% -- do_sym: Whether to symmetrize the matrix every k steps
% (default 0)
% -- do_psd: Whether to PSD the matrix every k steps, including
% symmetrizing them (defalut 0)
% -- do_save: Whether to save the intermediate matrices. Note that
% saving is before symmetrizing and/or PSD in case they exist
% (default 0)
% -- save_path: In case do_save==1 a filename is needed, the
% format is save_path/part_k.mat
% -- num_steps - Number of total steps the algorithm will
% run (default 1M steps)
% -- save_every: Number of steps between each save point
% (default num_steps/10)
% -- sym_every: An integer multiple of "save_every",
% indicates the frequency of symmetrizing in case do_sym=1. The
% end step will also be symmetrized. (default 1)
% -- psd_every: An integer multiple of "save_every",
% indicates the frequency of projecting on PSD cone in case
% do_psd=1. The end step will also be PSD. (default 1)
% -- use_matlab: Use oasis_m.m instead of oasis_c.c
% This is provided in the case of compilation problems.
%
I want to use this function, but I don't figure how to set the parameters, or use the default values. What is the variable parms in this case, it is an object that keep all the other variables? Can I make something python like syntax where we put the name of the parameter plus value? For example:
model = oasis(data_example, labels_example, agress = 0.2)
Additionally, If I have understood correctly, I get two Objects in the Output, which is model and modeo, so I need to make this call to receive all contents this function returns?
[model,modeo] = oasis(data_example, labels_example, ?(parms)?)
From your function definition it seems like params is simply a placeholder for the parameters. Typically the parameters themselves are passed as pairs of inputs in the form:
model = oasis(data, class_labels, 'do_sym',do_symValue, 'do_psd', do_psdValue,...)
where do_symValue and do_psdValue are the values you want to pass as the respective parameters.
As for the functions return value, it returns a single struct with members W, loss_steps, and parms. I believe that what you thought as a second output (modelo) is simply a typo in the text - at least based on the function's definition.
From the documentation above, I don't know which one is the right, but there are two common ways for optional parameters in matlab.
parameter value pairs:
model = oasis(data, class_labels, 'do_sym',1,'do_psd',0)
structs:
params.do_sym=1
params.do_psd=0
model = oasis(data, class_labels, params)
Probably one of these two possibilities is right.

MCC compiler "Internal Error: Could not determine class of method"

I have Matlab script that I am trying to compile as an executable that will run on a headless server as part of a large batch process. The script calls functions and classes written by several non-programmers (scientists) over the span of more than a decade, and I am having a difficult time getting it to compile.
The script will run in a Matlab instance, but MCC gives me an error that I do not quite understand:
Compiler version: 5.1 (R2014a)
Dependency analysis by REQUIREMENTS.
Error using matlab.depfun.internal.MatlabSymbol/proxy (line 405)
Internal1 Error: Could not determine class of method
"/home/me/MyCode/#tsd/Data.m". Number of classes checked:
17.
#tsd/tsd.m looks like this:
function tsa = tsd(t, Data)
% tsd Creates tsd object (tsd = class of timestamped arrays of data)
%
% tsa = tsd(t, Data)
%
% INPUTS:
% t - list of timestamps - must be sequential, but don't have to be continuous
% Data - data, possibly an array. If data is n-dimensional, then time should be the FIRST axis.
% OUTPUTS:
% tsa - a tsd object
%
% Completely compatible with ctsd.
%
% Methods
% tsd/Range - Timestamps used
% tsd/Data - Returns the data component
% tsd/DT - Returns the DT value (mean diff(timestamps))
% tsd/StartTime - First timestamp
% tsd/EndTime - Last timestamp
% tsd/Restrict - Keep data within a certain range
% tsd/CheckTS - Makes sure that a set of tsd & ctsd objects have identical start and end times
% tsd/cat - Concatenate ctsd and tsd objects
% tsd/Mask - Make all non-mask values NaN
%
% ADR 1998, version L4.0, last modified '98 by ADR
% RELEASED as part of MClust 2.0
% See standard disclaimer in ../Contents.m
if nargin == 0
tsa.t = NaN;
tsa.data = NaN;
tsa = class(tsa, 'tsd');
return
end
if nargin < 2
error('tsd constructor must be called with T, Data');
end
tsa.t = t;
tsa.data = Data;
tsa = class(tsa, 'tsd');
and the Data.m file:
function v = Data(tsa, ix)
% tsd/Data Retrieves data from tsd
%
% d = Data(tsa)
% d = Data(tsa, ix)
%
% INPUTS:
% tsa - tsd object
% ix - alignment list (timestamps)
% OUTPUTS:
% v - the tsa.Data
%
% if called with alignment list, returns those tsa.Data(ix)
% if called without, returns complete tsa.Data
%
% ADR 1998, version L4.1, last modified '98 by ADR
% RELEASED as part of MClust 2.0
% See standard disclaimer in ../Contents.m
switch nargin
case 2
f = findAlignment(tsa, ix);
v = SelectAlongFirstDimension(tsa.data,f);
case 1
v = tsa.data;
otherwise
error('Unknown number of input arguments');
end
So the script calling the tsd function runs just find in the Matlab session, but the compiler throws the error described above. This is my first time working with Matlab and I am totally stumped. There is another class with a method named "Data", but that shouldn't cause this problem, could it?
I was having the exact same problem and was able to come up with a workaround.
I was facing this problem when I was compiling the MATLAB library using the command
mcc -W cpplib:LibName -T link:lib main.m -a './' -d 'dll_destintaion_dir'
LibName: DLL name
main.m: MATLAB entry point
dll_destintaion_dir: destination where DLL created will be stored
The error was gone when I compiled using this command instead
mcc -W cpplib:LibName -T link:lib main.m -a 'full_path_of_project_folder/*'
-d 'dll_destintaion_dir'
Note: This method does not add folders recursively to the archive. So subfolders have to be added explicitly using another -a flag in the command shown above.

beginner:referencing a cell containing a zero matlab

So far I have got this code:
clear all; % clears all variables from your workspace
close all; % closes all figure windows
clc; % clears command window
%%=============================================
%%define number of trials and subjects
%%=============================================
njump=81;
nsbj=6;
%%
%%==============================================
%%defining size of cell that will be created
%%==============================================
data=cell(njump,1);
%%
%%==============================================
%%defining gravity and frame rate per second (fps)
%%==============================================
fps=0.001; %frames per second
g=-9.81; %acceleration
%%
%%==============================================
%%read in excel data in CSV format
%%===============================================
for i=1:njump;
x=sprintf('Trial%02d.csv',i),sprintf('Trial%02d',i),'A1:E7000';;% jump data
data{i}=xlsread(x,'A1:E7000');
%%===============================================
%%defining total no. of frames and time of flight
%tnf=total number of frames equal to zero
%n = nnz(X) returns the number of nonzero elements in matrix X.
%%===============================================
% myMax(i) = nanmax(data{i}(:,5));
% vals = find(data{i}(:,5) > (myMax(i) - 10));
% pointsInAir = numel(vals,i);
tnf(i,1) = size(data{i,1},1) - nnz(data{i,1}(:,5)); %number of zeros
tof(i)=tnf(i)*fps; %Time of flight is equal to this
jh(i,1)=(-g*(tof(i).^2)/8); %defining jump height
%%=================================================
%%to find average power first use "find" function to find the first zero in
%%Fz, have the cell referenced
%%then use nanmean for average power(av_pwr)
%%use nanmin for peak power (peak_pwr)
%%=================================================
n = 1; % the following call to find retrieves only the n first element(s) found.
ref= find(data{i,1}(:,5)==0, n, 'first');
% ref=find(data(:,5)==0);
peak_pwr(i,1) = nanmin (data {i,1}(1:ref,5)); %preak power in coloumn E1 in all data with reference to cell found
av_pwr(i,1)=nanmean(data {i,1}(1:ref,5));%average power in coloumn E1 in all data with reference to cell found
%%==================================================
%%Plot the results onto a time vs jump height, time vs average power and
%%time vs peak power
However the part that is hard is trying to find the first zero in column E which is the 5th column to use as a reference cell. I want to use this reference cell so that I can do my average and peak power calcs. that use the numbers before this zero.
In this case ref is empty so you cannot access the first element.
If you think that ref should not be empty you need to go back further to see where things go wrong. Otherwise, you can use something like:
if any(ref)
%Do something
else
%Return the default value/do alternative action
end
It could help to have an example of what's in data. I have created one which might be similar to yours :
data{1,1}=magic(6)-10
Now in this matrix, column 5 actually does have a zero element so ref= find(data{1,1}(:,5)==0); ref(1) actually works and retrieves the first index of a zero element. However, if it didn't, you would be trying to access the first element of an empty matrix.
Try instead using the second (and perhaps third) arguments of find to achieve this :
n = 1;
% the following call to find retrieves only the n first element(s) found.
ref= find(data{1,1}(:,5)==0, n, 'first');
The rest of your code seems like it should work, although from the looks of it i have a feeling your loop (i take it you are using a loop for i) could maybe be vectorized.
Hope this helps :)
Tepp

PCA codes input, use for PalmPrint Recognition

I'm new to Matlab.
I'm trying to apply PCA function(URL listed below)into my palm print recognition program to generate the eigenpalms. My palm print grey scale images dimension are 450*400.
Before using it, I was trying to study these codes and add some codes to save the eigenvector as .mat file. Some of the %comments added by me for my self understanding.
After a few days of studying, I still unable to get the answers.
I decided to ask for helps.I have a few questions to ask regarding this PCA.m.
PCA.m
What is the input of the "options" should be? of "PCA(data,details,options)"
(is it an integer for reduced dimension? I was trying to figure out where is the "options" value passing, but still unable to get the ans. The msgbox of "h & h2", is to check the codes run until where. I was trying to use integer of 10, but the PCA.m processed dimension are 400*400.)
The "eigvector" that I save as ".mat" file is ready to perform Euclidean distance classifier with other eigenvector? (I'm thinking that eigvector is equal to eigenpalm, like in face recognition, the eigen faces. I was trying to convert the eigenvector matrix back to image, but the image after PCA process is in Black and many dots on it)
mySVD.m
In this function, there are two values that can be changed, which are MAX_MATRIX_SIZE set by 1600 and EIGVECTOR_RATIO set by 0.1%. May I know these values will affect the results? ( I was trying to play around with the values, but I cant see the different. My palm print image dimension is set by 450*400, so the Max_matrix_size should set at 180,000?)
** I hope you guys able to understand what I'm asking, please help, Thanks guys (=
Original Version : http://www.cad.zju.edu.cn/home/dengcai/Data/code/PCA.m
mySVD: http://www.cad.zju.edu.cn/home/dengcai/Data/code/mySVD.m
% Edited Version by me
function [eigvector, eigvalue] = PCA(data,details,options)
%PCA Principal Component Analysis
%
% Usage:
% [eigvector, eigvalue] = PCA(data, options)
% [eigvector, eigvalue] = PCA(data)
%
% Input:
% data - Data matrix. Each row vector of fea is a data point.
% fea = finite element analysis ?????
% options.ReducedDim - The dimensionality of the reduced subspace. If 0,
% all the dimensions will be kept.
% Default is 0.
%
% Output:
% eigvector - Each column is an embedding function, for a new
% data point (row vector) x, y = x*eigvector
% will be the embedding result of x.
% eigvalue - The sorted eigvalue of PCA eigen-problem.
%
% Examples:
% fea = rand(7,10);
% options=[]; %store an empty matrix in options
% options.ReducedDim=4;
% [eigvector,eigvalue] = PCA(fea,4);
% Y = fea*eigvector;
%
% version 3.0 --Dec/2011
% version 2.2 --Feb/2009
% version 2.1 --June/2007
% version 2.0 --May/2007
% version 1.1 --Feb/2006
% version 1.0 --April/2004
%
% Written by Deng Cai (dengcai AT gmail.com)
%
if (~exist('options','var'))
%A = exist('name','kind')
% var = Checks only for variables.
%http://www.mathworks.com/help/matlab/matlab_prog/symbol-reference.html#bsv2dx9-1
%The tilde "~" character is used in comparing arrays for unequal values,
%finding the logical NOT of an array,
%and as a placeholder for an input or output argument you want to omit from a function call.
options = [];
end
h2 = msgbox('not yet');
ReducedDim = 0;
if isfield(options,'ReducedDim')
%tf = isfield(S, 'fieldname')
h2 = msgbox('checked');
ReducedDim = options.ReducedDim;
end
[nSmp,nFea] = size(data);
if (ReducedDim > nFea) || (ReducedDim <=0)
ReducedDim = nFea;
end
if issparse(data)
data = full(data);
end
sampleMean = mean(data,1);
data = (data - repmat(sampleMean,nSmp,1));
[eigvector, eigvalue] = mySVD(data',ReducedDim);
eigvalue = full(diag(eigvalue)).^2;
if isfield(options,'PCARatio')
sumEig = sum(eigvalue);
sumEig = sumEig*options.PCARatio;
sumNow = 0;
for idx = 1:length(eigvalue)
sumNow = sumNow + eigvalue(idx);
if sumNow >= sumEig
break;
end
end
eigvector = eigvector(:,1:idx);
end
%dt get from C# program, user ID and name
evFolder = 'ev\';
userIDName = details; %get ID and Name
userIDNameWE = strcat(userIDName,'\');%get ID and Name with extension
filePath = fullfile('C:\Users\***\Desktop\Data Collection\');
userIDNameFolder = strcat(filePath,userIDNameWE); %ID and Name folder
userIDNameEVFolder = strcat(userIDNameFolder,evFolder);%EV folder in ID and Name Folder
userIDNameEVFile = strcat(userIDNameEVFolder,userIDName); % EV file with ID and Name
if ~exist(userIDNameEVFolder, 'dir')
mkdir(userIDNameEVFolder);
end
newFile = strcat(userIDNameEVFile,'_1');
searchMat = strcat(newFile,'.mat');
if exist(searchMat, 'file')
filePattern = strcat(userIDNameEVFile,'_');
D = dir([userIDNameEVFolder, '*.mat']);
Num = length(D(not([D.isdir])))
Num=Num+1;
fileName = [filePattern,num2str(Num)];
save(fileName,'eigvector');
else
newFile = strcat(userIDNameEVFile,'_1');
save(newFile,'eigvector');
end
You pass options in a structure, for instance:
options.ReducedDim = 2;
or
options.PCARatio =0.4;
The option ReducedDim selects the number of dimensions you want to use to represent the final projection of the original matrix. For instance if you pick option.ReducedDim = 2 you use only the two eigenvectors with largest eigenvalues (the two principal components) to represent your data (in effect the PCA will return the two eigenvectors with largest eigenvalues).
PCARatio instead allows you to pick the number of dimensions as the first eigenvectors with largest eigenvalues that account for fraction PCARatio of the total sum of eigenvalues.
In mySVD.m, I would not increase the default values unless you expect more than 1600 eigenvectors to be necessary to describe your dataset. I think you can safely leave the default values.

explanation for matlab code

Am new to matlab.
Can someone explain me the following code. this code is used for training the neural network
N = xlsread('data.xls','Sheet1');
N = N(1:150,:);
UN = xlsread('data.xls','Sheet2');
UN = UN(1:150,:);
traindata = [N ; UN];
save('traindata.mat','traindata');
label = [];
for i = 1 : size(N,1)*2
if( i <= size(N,1))
% label = [label ;sum(traindata(i,:))/size(traindata(i,:),2)];
label = [label ;sum(traindata(i,:))/10];
else
% label = [label ;sum(traindata(i,:))/size(traindata(i,:),2)];
label = [label ;sum(traindata(i,:))/10];
end
end
weightMat = BpTrainingProcess(4,0.0001,0.1,0.9,15,[size(traindata,1) 1],traindata,label);
I cannot find a Neural Network toolbox built-in that corresponds to BpTrainingProcess(), so this must be a file you have access to locally (or you need to obtain from the person who gave you this code). It likely strings together several function calls to Neural Network toolbox functions, or perhaps is an original implementation of a back-propagation training method.
Otherwise, the code has some drawbacks. For one, it doesn't appear that the interior if-else statement actually does anything. Even the lines that are commented out would leave a totally useless if-else setup. It looks like the if-else is intended to let you do different label normalization for the data loaded from Sheet1 of the Excel file vs. data loaded from Sheet2. Maybe that is important for you, but it's currently not happening in the program.
Lastly, the code uses an empty array for label and the proceeds to append rows to the empty array. This is unneeded because you already know how many rows there will be (it will total up to size(N,1)*2 = 150*2 = 300 rows. You could just as easily set label=zeros(300,1) and then use usual indexing at each iteration of the for-loop: label(i) = .... This saves time and space, but arguably won't matter much for a 300-row data set (assuming that the length of each row is not too large).
I put documentation next to the code below.
% The functionn 'xlsread()' reads data from an Excel file.
% Here it is storing the values from Sheet 1 of the file 'data.xls'
% into the variable N, and then using the syntax N = N(1:150,:) to
% change N from being all of the data into being only the first
% 150 rows of the data
N = xlsread('data.xls','Sheet1');
N = N(1:150,:);
% Now do the same thing for Sheet 2 from the Excel file.
UN = xlsread('data.xls','Sheet2');
UN = UN(1:150,:);
% This concatenates the two different data arrays together, making
% one large array where N is the top half and UN is the bottom half.
% This is basically just stacking N on top of UN into one array.
traindata = [N ; UN];
% This saves a copy of the newly stacked array into the Matlab data file
% 'traindata.mat'. From now on, you should be able to load the data from
% this file, without needing to read it from the Excel sheet above.
save('traindata.mat','traindata');
% This makes an empty array which will have new things appended to it below.
label = [];
% Because UN and N have the same number of rows, then the training data
% has twice as many rows. So this sets up a for loop that will traverse
% all of these rows of the training data. The 'size()' function can be
% used to get the different dimensions of an array.
for i = 1 : size(N,1)*2
% Here, an if statement is used to check if the current row number, i,
% is less than or equal to than the number of rows in N. This implies
% that this part of the if-statement is only for handling the top half
% of 'trainingdata', that is, the stuff coming from the variable N.
if( i <= size(N,1))
% The line below was already commented out. Maybe it had an old use
% but is no longer needed?
% label = [label ;sum(traindata(i,:))/size(traindata(i,:),2)];
% This syntax will append new rows to the variable 'label', which
% started out as an empty array. This is usually bad practice, memory-wise
% and also for readability.
% Here, the sum of the training data is being computed, and divided by 10
% in every case, and then appended as a new row in 'label'. Hopefully,
% if you are familiar with the data, you will know why the data in 'N'
% always needs to be divided by 10.
label = [label ;sum(traindata(i,:))/10];
% Otherwise, if i > # of rows then handle the data differently.
% Really this means the code below treats only data from the variable UN.
else
% The line below was already commented out. Maybe it had an old use
% but is no longer needed?
% label = [label ;sum(traindata(i,:))/size(traindata(i,:),2)];
% Just like above, the data is being divided by 10. Given that there
% is nothing different about the code here, and how it modifies 'label'
% there is no need for the if-else statements, and they only waste time.
label = [label ;sum(traindata(i,:))/10];
% This is needed to show the end of the if-else block.
end
% This is needed to show the end of the for-loop.
end
% This appears to be a Back-Propagation Neural Network training function.
% This doesn't match any built-in Matlab function I can find, but you might
% check in the Neural Network toolbox to see if the local function
% BpTrainingProcess is a wrapper for a collection of built-in training functions.
weightMat = BpTrainingProcess(4, 0.0001, 0.1, 0.9, 15,
[size(traindata,1) 1], traindata,label);
Here is a link to an example Matlab Neural Network toolbox function for back-propagation training. You might want to look around the documentation there to see if any of it resembles the interior of BpTrainingProcess().