Octave invalid use of script in index expression - statistics

I try to use the fitgmdist.m to fit a gaussian mixture model. However, when it call the constructor of class gmdistribution.I got the error messgae as below:
error: invalid use of script /home/ubuntu/UAVProject_DataStructure/gmdistribution.m in index expression
error: called from:
error: /home/ubuntu/UAVProject_DataStructure/fitgmdist.m at line 505, column 7
error: /home/ubuntu/UAVProject_DataStructure/computeGMM.m at line 78, column 10
error: /home/ubuntu/UAVProject_DataStructure/ImageProcessing.m at line 18, column 13
I put the 2 files: fitgmdist.m and gmdistribution.m in the current directory.
And I also change gmdistribution.m name to avoid having the same name of the octave library's file, but it doesn't work. Can someone help? Thanks.
Here is calling the constructor code:
obj = gmdistribution (best_params.mu, best_params.Sigma, best_params.p');
Here is the constructor Code:
########################################
## Constructor
function obj = gmdistribution (mu,sigma,p = [],extra = [])
obj.DistributionName = "gaussian mixture distribution";
obj.mu = mu;
obj.Sigma = sigma;
obj.NumComponents = rows (mu);
obj.NumVariables = columns (mu);
if (isempty (p))
obj.ComponentProportion = ones (1,obj.NumComponents) / obj.NumComponents;
else
if any (p < 0)
error ("gmmdistribution: component weights must be non-negative");
endif
s = sum(p);
if (s == 0)
error ("gmmdistribution: component weights must not be all zero");
elseif (s != 1)
p = p / s;
endif
obj.ComponentProportion = p(:)';
endif
if (length (size (sigma)) == 3)
obj.SharedCovariance = false;
else
obj.SharedCovariance = true;
endif
if (rows (sigma) == 1 && columns (mu) > 1)
obj.DiagonalCovariance = true;
obj.CovarianceType = 'diagonal';
else
obj.DiagonalCovariance = false; ## full
obj.CovarianceType = 'full';
endif
if (!isempty (extra))
obj.AIC = extra.AIC;
obj.BIC = extra.BIC;
obj.Converged = extra.Converged;
obj.NegativeLogLikelihood = extra.NegativeLogLikelihood;
obj.NlogL = extra.NegativeLogLikelihood;
obj.NumIterations = extra.NumIterations;
obj.RegularizationValue = extra.RegularizationValue;
endif
endfunction

Related

How to define a partial copy constructor metaprogramically in Julia?

Gadfly has a nifty macro that generates a copy constructor and optional argument constructor for some large types:
# Generate large types where each field has a default value to which it's
# initialized.
macro varset(name::Symbol, table)
#assert table.head == :block
table = table.args
names = Any[]
vars = Any[]
parameters = Any[]
parameters_expr = Expr(:parameters)
for row in table
if isa(row, Expr) && row.head == :line
continue
end
if isa(row, Symbol)
var = row
typ = :Any
default = :nothing
elseif row.head == :tuple
#assert 2 <= length(row.args) <= 3
var = row.args[1]
typ = row.args[2]
default = length(row.args) > 2 ? row.args[3] : :nothing
else
error("Bad varset systax")
end
push!(names, var)
push!(vars, :($(var)::$(typ)))
push!(parameters, Expr(:kw, var, default))
parameters_expr = Expr(:parameters, parameters...)
end
new_with_defaults = Expr(:call, :new, names...)
ex =
quote
type $(name)
$(vars...)
function $(name)($(parameters_expr))
$(new_with_defaults)
end
# shallow copy constructor
function $(name)(a::$(name))
b = new()
for name in fieldnames($(name))
setfield!(b, name, getfield(a, name))
end
b
end
end
function copy(a::$(name))
$(name)(a)
end
end
esc(ex)
end
I would like to add a partial copy constructor that lets you provide an object and some partial parameters. It would copy the provided object and overwrite only the fields that you give it.
How could I define something like the following? Pseudocode-ish:
function $(name)(a::$(name), $(parameters_expr))
b = new(a)
for name in names
if getfield(b, name) != default
setfield!(b, name, new_val)
end
end
end

Compile-time Call Count in Nim

The following code does not compile but illustrates what I would like to do: totalTests should hold the number of time that assertEquals() is called (assertEquals() should probably be a macro for this to be possible, but I'm not familiar with this aspect of Nim yet).
Any idea how this code should be modified to enable the following code to print [1/2] and [2/2] at the beginning of each test report line?
from strutils import format
var countTested = 0
var countFailed = 0
var countPassed = 0
let totalTests = 0 # <-- need let or other compile-time type here (?)
# using proc here... macro may be needed to be able to count calls (?)
proc assertEquals*[T](testName: string, expected: T, p: (proc(): T)) =
countTested += 1
totalTests += 1 # <-- compilation error (how can we increase each time it is called?)
write(stdout, format("[$num/$total] $name: ", "num", countTested, "total", totalTests, "name", testName))
var val = p()
if val == expected:
write(stdout, "passed\n")
countPassed += 1
else:
write(stdout, "failed\n")
countFailed += 1
when isMainModule:
assertEquals("test #A", 12, proc(): int = 14-2)
assertEquals("test #B", 12, proc(): int = 12-2)
Edit: added questions in code
Here is one way to do it. You can execute code at compile time by using a macro or a static statement. Note that there's still no way to reliably count these across multiple modules.
import macros, strutils
proc beginTests()
var countTested = 0
var countFailed = 0
var countPassed = 0
var totalTests = 0
var totalTestsCT {.compiletime.} = 0
macro endTests(): stmt =
quote do:
proc beginTests() =
totalTests = `totalTestsCT`
proc assertEqualsImpl*[T](testName: string, expected: T, p: (proc(): T)) =
countTested += 1
write(stdout, format("[$num/$total] $name: ",
"num", countTested, "total", totalTests, "name", testName))
var val = p()
if val == expected:
write(stdout, "passed\n")
countPassed += 1
else:
write(stdout, "failed\n")
countFailed += 1
macro assertEquals*[T](testName: string, expected: T, p: (proc(): T)): stmt =
totalTestsCT += 1
quote do:
assertEqualsImpl(`testName`, `expected`, `p`)
when isMainModule:
beginTests()
assertEquals("test #A", 12, proc(): int = 14-2)
assertEquals("test #B", 12, proc(): int = 12-2)
endTests()
An alternative implementation would be to embed the tests in a custom block statement, e.g.
testSuite:
assertEquals("test #A", 12, proc(): int = 14-2)
assertEquals("test #B", 12, proc(): int = 12-2)
The testSuite macro would then count the assertions in the embedded code and initialize the variable accordingly.
Yet another solution would be to not execute the tests directly, but store them in a list and only execute them at the end.
Here is an implementation of Reimer's third suggestion, which worked best for me.
import macros, strutils
type
TestSuiteObj = object
countTested: int
countFailed: int
countPassed: int
totalTests: int
tests: seq[(proc (self: TestSuite))]
TestSuite* = ref TestSuiteObj
proc newTestSuite*(): TestSuite =
new(result)
result.countTested = 0
result.countFailed = 0
result.countPassed = 0
result.totalTests = 0
result.tests = #[]
proc assertEquals*[T](self: TestSuite, testName: string, expected: T, p: (proc(): T)) =
self.totalTests += 1
var testProc = proc(self: TestSuite) =
self.countTested += 1
write(stdout, format("[$num/$total] $name: ", "num", self.countTested, "total", self.totalTests, "name", testName))
var val = p()
if val == expected:
write(stdout, "passed\n")
self.countPassed += 1
else:
write(stdout, "failed\n")
self.countFailed += 1
self.tests.add(testProc)
proc run*(self: TestSuite) =
self.totalTests = self.tests.len
for p in self.tests:
p(self)
var verdict = case (self.countTested == self.countPassed)
of true: "PASSED"
of false: "FAILED"
echo format("$verdict. Passed [$passed/$total] tests.", "verdict", verdict, "passed", self.countPassed, "total", self.countTested)
# Sanity
assert(self.countTested == (self.countFailed+self.countPassed))
assert(self.countTested == self.totalTests)
when isMainModule:
var suite = newTestSuite()
suite.assertEquals("test #A", 12, proc(): int = 14-2)
suite.assertEquals("test #B", 12, proc(): int = 12-2)
suite.run()

Compare to string of names

I am trying to compare the names of two strings, and trying to pick out the name that are not included in the other string.
h = 1;
for i = 1:name_size_main
checker = 0;
main_name = main(i);
for j = 1:name_size_image
image_name = image(j);
temp = strcmpi(image_name, main_name);
if temp == 1;
checker = temp;
end
end
if checker == 0
result(h) = main_name;
h = h+1;
end
end
but it keeps returning the entire string as result, the main string contain roughly 1000 names, the images name contain about 300 names, so it should return about 700 names in result but it keep returning all 1000 names.
I tried your code with small vectors:
main = ['aaa' 'bbb' 'ccc' 'ddd'];
image = ['bbb' 'ddd'];
name_size_main = size(main,2);
name_size_image = size(image,2);
h = 1;
for i = 1:name_size_main
checker = 0;
main_name = main(i);
for j = 1:name_size_image
image_name = image(j);
temp = strcmpi(image_name, main_name);
if temp == 1;
checker = temp;
end
end
if checker == 0
result(h) = main_name;
h = h+1;
end
end
I get result = 'aaaccc', is it not what you want to get?
EDIT:
If you are using cell arrays, you should change the line result(h) = main_name; to result{h} = main_name; like that:
main = {'aaa' 'bbb' 'ccc' 'ddd'};
image = {'bbb' 'ddd'};
name_size_main = size(main,2);
name_size_image = size(image,2);
result = cell(0);
h = 1;
for i = 1:name_size_main
checker = 0;
main_name = main(i);
for j = 1:name_size_image
image_name = image(j);
temp = strcmpi(image_name, main_name);
if temp == 1;
checker = temp;
end
end
if checker == 0
result{h} = main_name;
h = h+1;
end
end
You can use cells of string along with setdiff or setxor.
A = cellstr(('a':'t')') % a cell of string, 'a' to 't'
B = cellstr(('f':'z')') % 'f' to 'z'
C1 = setdiff(A,B,'rows') % gives 'a' to 'e'
C2 = setdiff(B,A,'rows') % gives 'u' to 'z'
C3 = setxor(A,B,'rows') % gives 'a' to 'e' and 'u' to 'z'

Groovy: indexes of substrings?

How do I find the indexes of all the occurances of a substring in a large string -
(so basically ,and extension of the "indexOf" function) . Any ideas?
Current situation:
def text = " --- --- bcd -- bcd ---"
def sub = "bcd"
text.indexOf(sub)
// = 9
I want something like:
def text = " --- --- bcd -- bcd ---"
def sub = "bcd"
text.indexesOf(sub)
// = [9,15]
Is there such a function? How should I implement it otherwise? (in a non trivial way)
You could write a new addition to the String metaClass like so:
String.metaClass.indexesOf = { match ->
def ret = []
def idx = -1
while( ( idx = delegate.indexOf( match, idx + 1 ) ) > -1 ) {
ret << idx
}
ret
}
def text = " --- --- bcd -- bcd ---"
def sub = "bcd"
text.indexesOf(sub)
There is nothing I know of that exists in groovy currently that gets you this for free though
This is a relatively easy approach:
String.metaClass.indexesOf = { arg ->
def result = []
int index = delegate.indexOf(arg)
while (index != -1) {
result.add(index);
index = delegate.indexOf(arg, index+1);
}
return result;
}
Note that this will find overlapping instances (i.e. "fooo".indexesOf("oo") will return [1, 2]). If you don't want this, replace index+1 with index+arg.length().

Get context for search string in text in C#

Given a string text which contains newline there is a search keyword which matches an item within the text.
How do I implement the following in C#:
searchIdx = search index (starting with 0, then 1, etc. for each successive call to GetSearchContext. Initially start with 0.
contextsTxt = string data to search in
searchTxt = keyword to search for in contextsTxt
numLines = number of lines to return surrounding the searchTxt found (ie. 1 = the line the searchTxt is found on, 2 = the line the searchTxt is found on, 3 = the line above the searchTxt is found on, the line the searchTxt is found on, and the line below the searchTxt is found on)
returns the "context" based on the parameters
string GetSearchContext(int searchIdx, string contentsTxt, string searchTxt, int numLines);
If there's a better function interface to accomplish this feel free to suggest that as well.
I tried the following but doesn't seem to work properly all the time:
private string GetSearchContext(string contentValue, string search, int numLines)
{
int searchIdx = contentValue.IndexOf(search);
int startIdx = 0;
int lastIdx = 0;
while (startIdx != -1 && (startIdx = contentValue.IndexOf('\n', startIdx+1)) < searchIdx)
{
lastIdx = startIdx;
}
startIdx = lastIdx;
if (startIdx < 0)
startIdx = 0;
int endIdx = searchIdx;
int lineCnt = 0;
while (endIdx != -1 && lineCnt++ < numLines)
{
endIdx = contentValue.IndexOf('\n', endIdx + 1);
}
if (endIdx == -1 || endIdx > contentValue.Length - 1)
endIdx = contentValue.Length - 1;
string lines = contentValue.Substring(startIdx, endIdx - startIdx + 1);
if (lines[0] == '\n')
lines = lines.Substring(1);
if (lines[lines.Length - 1] == '\n')
{
lines = lines.Substring(0, lines.Length - 1);
}
if (lines[lines.Length - 1] == '\r')
{
lines = lines.Substring(0, lines.Length - 1);
}
return lines;
}
it's not actually a homework question. i'm trying to build a personal search engine. I just now figured out the problem as to why it didn't always work which was due to case-sensitive searching.
Just needed to add StringComparison.CurrentCultureIgnoreCase and voila it worked! I feel dumb for not thinking of that before posting.

Resources