How to order a list of delaunay triangles to a ordered percolation list in Octave? - octave

Given a list of all triangles
v2_T = delaunay(v2_p)
from a list of all points "v2_p" and given a list of all triangle neighbors
v2_N = neighbors(v2_T)
how can I order "v2_T" such that starting from the first triangle going up, the next triangle you find in "v2_T" will always have at least one triangle neighbor I have listed previously. The closet function I can think of that performs a similar task might be a binary tree search or something involving a recursive algorithm.
Could someone provide sample Octave code? Thanks.

Here is my uncommitted solution to the above question. This is a dynamically linked function for Octave written in c++ with file name "dlf_percolate.cc". To compile this function use the command system('mkoctfile filedirectory/dlf_percolate.cc') or the alternative command mkoctfile "filedirectory/dlf_percolate.cc" in the octave terminal, where one must designate the file directory "filedirectory" of where the file "dlf_percolate.cc" is saved. To test the function v1_I = dlf_percolate(v2_N), one needs a generated list of neighbors v2_N = neighbors(v2_T), where v2_T is the generated list of delaunay triangles and neighbors() is a function that does not exist in Octave yet. Neighbors v2_N can be calculated from using functions used in the package "msh" http://octave.sourceforge.net/msh/. Once one has v2_N, one can compute the order of numerical labeled triangles in percolated order as v1_I = dlf_percolate(v2_N,v_first_neigh), where "v_first_neigh" is the first triangle to start calculating the percolated order of listed triangles "v1_I".
#include <octave/oct.h>
void func_perc
(
Matrix & v2_neigh_list
,
ColumnVector & v1_perc_list
,
ColumnVector & b1_toggled_neigh
,
int & v0_perc_index
,
int v0_next_neigh
) ;
DEFUN_DLD (dlf_percolate, args, ,
"Returns a list of sorted indices of the neighbors in percolated order."
) {
int v0_first_neigh = 1 ;
switch( args.length() )
{
case 1:
// v0_first_neigh = 1 default value
break;
case 2:
v0_first_neigh = args(1).scalar_value() ;
break;
default:
error("Only one or two inputs are needed!") ;
return args;
break;
}
octave_value_list o1_retval ;
Matrix v2_neigh_list = args(0).matrix_value() ;
int v0_cols = v2_neigh_list.cols();
int v0_rows = v2_neigh_list.rows();
if( ( v0_first_neigh <= 0 ) || ( v0_rows < v0_first_neigh ) )
{
error("v0_first_neigh must be a valid member of the list!") ;
return args;
}
ColumnVector v1_perc_list(v0_rows,0);
ColumnVector b1_toggled_neigh(v0_rows,false);
int v0_perc_index = 0 ;
func_perc
(
v2_neigh_list
,
v1_perc_list
,
b1_toggled_neigh
,
v0_perc_index
,
v0_first_neigh
) ;
o1_retval(0) = v1_perc_list ;
return o1_retval ;
}
void func_perc
(
Matrix & v2_neigh_list
,
ColumnVector & v1_perc_list
,
ColumnVector & b1_toggled_neigh
,
int & v0_perc_index
,
int v0_next_neigh
)
{
if
(
( v0_next_neigh > 0 )
&&
( ( v0_perc_index ) < v1_perc_list.length() )
&&
( b1_toggled_neigh( v0_next_neigh - 1 ) == false )
)
{
v1_perc_list( v0_perc_index ) = v0_next_neigh ;
v0_perc_index++;
b1_toggled_neigh( v0_next_neigh - 1 ) = true ;
for( int v0_i = 0 ; v0_i < v2_neigh_list.cols() ; v0_i++ )
{
func_perc
(
v2_neigh_list
,
v1_perc_list
,
b1_toggled_neigh
,
v0_perc_index
,
v2_neigh_list( v0_next_neigh - 1 , v0_i )
) ;
}
}
return ;
}
I believe any calculated percolation path must involve a recursive algorithm. If not, at minimum, recursion makes easier code implementation to solve these types of problems. The first build I designed for this function in Octave script called an Octave function recursively which ran progressively slower at each step of the recursive algorithm. I believe recursion in Octave functions is not very efficient, because of the functional over headed of the interpretive language. Writing native functions in c++ for Octave is a better way to implement recursive algorithms efficiently. The c++ function func_perc() is the recursive algorithm used in dlf_percolate().

Related

Use varargin for multiple arguments with default values in MATLAB

Is there a way to supply arguments using varargin in MATLAB in the following manner?
Function
func myFunc(varargin)
if a not given as argument
a = 2;
if b not given as argument
b = 2;
if c not given as argument
c = a+b;
d = 2*c;
end
I want to call the above function once with b = 3 and another time while the previous one is running in the same command window with a = 3 and c = 3 and letting b take the default value in the function this time. How can it be done using varargin?
Here's the latest and greatest way to write the function (using arguments blocks from R2019b)
function out = someFcn(options)
arguments
options.A = 3;
options.B = 7;
options.C = [];
end
if isempty(options.C)
options.C = options.A + options.B;
end
out = options.A + options.B + options.C;
end
Note that this syntax does not allow you to say options.C = options.A + options.B directly in the arguments block.
In MATLAB < R2021a, you call this like so
someFcn('A', 3)
In MATLAB >= R2021a, you can use the new name=value syntax
someFcn(B = 7)
Here are two ways to do this which have been available since 2007a (i.e. a long time!). For a much newer approach, see Edric's answer.
Use nargin and ensure your inputs are always in order
Use name-value pairs and an input parser
nargin: slightly simpler but relies on consistent input order
function myFunc( a, b, c )
if nargin < 1 || isempty(a)
a = 2;
end
if nargin < 2 || isempty(b)
b = 2;
end
if nargin < 3 || isempty(c)
c = a + b;
end
end
Using the isempty check you can optionally provide just later arguments, for example myFunc( [], 4 ) would just set b=4 and use the defaults otherwise.
inputParser: more flexible but can't directly handle the c=a+b default
function myFunc( varargin )
p = inputParser;
p.addOptional( 'a', 2 );
p.addOptional( 'b', 2 );
p.addOptional( 'c', NaN ); % Can't default to a+b, default to NaN
p.parse( varargin{:} );
a = p.Results.a;
b = p.Results.b;
c = p.Results.c;
if isnan(c) % Handle the defaulted case
c = a + b;
end
end
This would get used like myFunc( 'b', 4 );. This approach is also agnostic to the input order because of the name-value pairs, so you can also do something like myFunc( 'c', 3, 'a', 1 );

Octave error: element undefined in return list

I am writing the following octave code:
function p = predict(Theta1, Theta2, X)
m = size(X, 1);
num_labels = size(Theta2, 1);
global a=zeros(size(Theta2, 2), m);
global delta=zeros(m, 1);
p = zeros(size(X, 1), 1);
X=[ones(size(X,1),1) X];
a=sigmoid(Theta1*X');
a=[ones(1,size(X,1));a];
[delta p]=max(sigmoid(Theta2*a))';
It gives me the error: "element number 2 undefined in return list".
The error occurs when I use delta in the last line to store max values.
I have searched a lot but couldn't find any relevant answer.
The line
[delta p] = max( sigmoid( Theta2*a ) )'; # transpose operator over the result
is equivalent to
[delta p] = transpose( max( sigmoid( Theta2*a ) ); # transpose function over the result
which means you are trying to get a "two-output" result out of this transpose operation, which fails, since the transpose function only returns one output, therefore octave is informing you that it cannot find a second output in the 'results' list.
Presumably you either meant to do something along the lines of:
[delta p] = max( sigmoid( Theta2*a )' );
and misplaced the transpose operator, or you actually did want to obtain the maxima and their indices as a column vector, in which case you need to do this in two steps, i.e.
[delta p] = max( sigmoid( Theta2*a ) );
ColVector = [delta p]';
PS. Incidentally, you should use .' instead of ' as the transpose operator. ' is not the transpose operator, it's the "conjugate transpose" one.

Minizinc: Pairwise intersection of int arrays

I have some arrays (can be more than 10) of int variables. I am looking for an efficient way to constraint the pairwise intersection count of these arrays, i.e that each array cannot have more than x elements in common with any other array.
Example in pseudocode: [1,4,4] and [2,2,1] would have one element in common -> the number 1. [4,4,4] and [9,4,4] have the element 4 in common, the duplicate 4 should be ignored.
In my current implementation, I iterate over all pairs of arrays and for each par check for each element if it is in the other array as well. This is of course very slow and the duplicates are not eliminated as they should be.
The interesting part of my code looks like this:
constraint matches [0] = exists ( i in index_set(values1) ) ( values1[i]==values2[0] );
constraint matches [1] = exists ( i in index_set(values1) ) ( values1[i]==values2[1] );
constraint matches [2] = exists ( i in index_set(values1) ) ( values1[i]==values2[2] );
constraint matches [3] = exists ( i in index_set(values1) ) ( values1[i]==values2[3] );
constraint matches [4] = exists ( i in index_set(values1) ) ( values1[i]==values2[4] );
constraint sum(matches) < x;
I have thought about using minizinc sets as they support some set operations, but I could not get them to work with variables.
Any ideas?
Perhaps something like this, using array2set for converting the arrays to sets and then card and intersect to calculate the number of intersections between each pair.
int: rows = 4; % number of columns
int: cols = 5; % number of rows
array[1..rows,1..cols] of int: a = array2d(1..rows,1..cols,
[
4,6,9,5,6,
5,3,7,1,3,
3,8,3,3,1,
1,1,4,7,2,
]);
% convert the arrays to sets
array[1..rows] of set of int: s = [array2set([a[i,j] | j in 1..cols]) | i in 1..rows];
% decision variables
var int: z;
solve satisfy;
constraint
z = sum(r1,r2 in 1..rows where r1 < r2) (
card(s[r1] intersect s[r2])
)
;
output
[
"z:\(z)\n"
] ++
[
show(s[i]) ++ "\n"
| i in 1..rows
];
The output of this model is
z:7
{4,5,6,9}
{1,3,5,7}
{1,3,8}
{1,2,4,7}

How to Find all occurrences of a Substring in C

I am trying to write a parsing program in C that will take certain segments of text from an HTML document. To do this, I need to find every instance of the substring "name": in the document; however, the C function strstr only finds the first instance of a substring. I cannot find a function that finds anything beyond the first instance, and I have considered deleting each substring after I find it so that strstr will return the next one. I cannot get either of these approaches to work.
By the way, I know the while loop limits this to six iterations, but I was just testing this to see if I could get the function to work in the first place.
while(entry_count < 6)
{
printf("test");
if((ptr = strstr(buffer, "\"name\":")) != NULL)
{
ptr += 8;
int i = 0;
while(*ptr != '\"')
{
company_name[i] = *ptr;
ptr++;
i++;
}
company_name[i] = '\n';
int j;
for(j = 0; company_name[j] != '\n'; j++)
printf("%c", company_name[j]);
printf("\n");
strtok(buffer, "\"name\":");
entry_count++;
}
}
Just pass the returned pointer, plus one, back to strstr() to find the next match:
char *ptr = strstr(buffer, target);
while (ptr) {
/* ... do something with ptr ... */
ptr = strstr(ptr+1, target);
}
Ps. While you certainly can do this, I'd like to suggest the you may wish to consider more suitable tools for the job:
C is a very low-level language, and trying to write string parsing code in it is laborious (especially if you insist on coding everything from scratch, instead of using existing parsing libraries or parser generators) and prone to bugs (some of which, like buffer overruns, can create security holes). There are plenty of higher-level scripting languages (like Perl, Ruby, Python or even JavaScript) that are much better suited for tasks like this.
When parsing HTML, you really should use a proper HTML parser (preferably combined with a good DOM builder and query tool). This will allow you to locate the data you want based on the structure of the document, instead of just matching substrings in the raw HTML source code. A real HTML parser will also transparently take care of issues like character set conversion and decoding of character entities. (Yes, there are HTML parsers for C, such as Gumbo and Hubbub, so you can and should use one even if you insist on sticking to C.)
/* * * * * * * * * * * * * * * * * *\
* *
* SubStg with parameters in the execution line *
* Must use 2 parameters *
* The 1st is the string to be searched *
* The 2nd is the substring *
* e.g.: ./Srch "this is the list" "is" >stuff *
* e.g.: ./Srch "$(<Srch.c)" "siz" *
* (ref: http://1drv.ms/1PuVpzS) *
* © SJ Hersh 15-Jun-2020 *
* *
\* * * * * * * * * * * * * * * * * */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char* char_ptr;
typedef unsigned int* int_ptr;
#define NOMEM ( int_ptr )0
int main( int parm, char** stgs )
{
char_ptr string, substg;
unsigned int sizstg, sizsub, endsiz, *ary;
int_ptr startmem;
register unsigned int x, y, ctr=0;
if( parm != 3 )
{
printf( "ERR: You need exactly 2 string arguments\n" );
return ( -8 );
}
string = stgs[ 1 ];
substg = stgs[ 2 ];
sizstg = strlen( string );
sizsub = strlen( substg );
endsiz = sizstg - sizsub + 1;
/* Check boundary conditions: */
if( ( sizstg == 0 ) || ( sizsub == 0 ) )
{
printf( "ERR: Neither string can be nul\n" );
return( -6 );
}
if( sizsub > sizstg )
{
printf( "ERR: Substring is larger than String\n" );
return( -7 );
}
if( NOMEM == ( ary = startmem = malloc( endsiz * sizeof( int ) ) ) )
{
printf( "ERR: Not enough memory\n" );
return( -9 );
}
/* Algorithm */
printf( "Positions:\t" );
for( x = 0; x < endsiz; x++ )
*ary++ = string[ x ] == substg[ 0 ];
for( y = 1, ary = startmem; y < sizsub; y++, ary = startmem )
for( x = y; x < ( endsiz + y ); x++ )
*ary++ &= string[ x ] == substg[ y ];
for( x = 0; ( x < endsiz ); x++ )
if( *ary++ )
{
printf( "%d\t", x );
ctr++;
}
printf( "\nCount:\t%d\n", ctr );
free( startmem );
return( 0 );
}

Implementing parts of rfc4226 (HOTP) in mysql

Like the title says, I'm trying to implement the programmatic parts of RFC4226 "HOTP: An HMAC-Based One-Time Password Algorithm" in SQL. I think I've got a version that works (in that for a small test sample, it produces the same result as the Java version in the code), but it contains a nested pair of hex(unhex()) calls, which I feel can be done better. I am constrained by a) needing to do this algorithm, and b) needing to do it in mysql, otherwise I'm happy to look at other ways of doing this.
What I've got so far:
-- From the inside out...
-- Concatinate the users secret, and the number of time its been used
-- find the SHA1 hash of that string
-- Turn a 40 byte hex encoding into a 20 byte binary string
-- keep the first 4 bytes
-- turn those back into a hex represnetation
-- convert that into an integer
-- Throw away the most-significant bit (solves signed/unsigned problems)
-- Truncate to 6 digits
-- store into otp
-- from the otpsecrets table
select (conv(hex(substr(unhex(sha1(concat(secret, uses))), 1, 4)), 16, 10) & 0x7fffffff) % 1000000
into otp
from otpsecrets;
Is there a better (more efficient) way of doing this?
I haven't read the spec, but I think you don't need to convert back and forth between hex and binary, so this might be a little more efficient:
SELECT (conv(substr(sha1(concat(secret, uses)), 1, 8), 16, 10) & 0x7fffffff) % 1000000
INTO otp
FROM otpsecrets;
This seems to give the same result as your query for a few examples I tested.
This is absolutely horrific, but it works with my 6-digit OTP tokens. Call as:
select HOTP( floor( unix_timestamp()/60), secret ) 'OTP' from SecretKeyTable;
drop function HOTP;
delimiter //
CREATE FUNCTION HOTP(C integer, K BINARY(64)) RETURNS char(6)
BEGIN
declare i INTEGER;
declare ipad BINARY(64);
declare opad BINARY(64);
declare hmac BINARY(20);
declare cbin BINARY(8);
set i = 1;
set ipad = repeat( 0x36, 64 );
set opad = repeat( 0x5c, 64 );
repeat
set ipad = insert( ipad, i, 1, char( ascii( substr( K, i, 1 ) ) ^ 0x36 ) );
set opad = insert( opad, i, 1, char( ascii( substr( K, i, 1 ) ) ^ 0x5C ) );
set i = i + 1;
until (i > 64) end repeat;
set cbin = unhex( lpad( hex( C ), 16, '0' ) );
set hmac = unhex( sha1( concat( opad, unhex( sha1( concat( ipad, cbin ) ) ) ) ) );
return lpad( (conv(hex(substr( hmac, (ascii( right( hmac, 1 ) ) & 0x0f) + 1, 4 )),16,10) & 0x7fffffff) % 1000000, 6, '0' );
END
//
delimiter ;