plateform
stringclasses 1
value | repo_name
stringlengths 13
113
| name
stringlengths 3
74
| ext
stringclasses 1
value | path
stringlengths 12
229
| size
int64 23
843k
| source_encoding
stringclasses 9
values | md5
stringlengths 32
32
| text
stringlengths 23
843k
|
---|---|---|---|---|---|---|---|---|
github
|
medooze/swig-master
|
cpp11_strongly_typed_enumerations_runme.m
|
.m
|
swig-master/Examples/test-suite/octave/cpp11_strongly_typed_enumerations_runme.m
| 9,095 |
utf_8
|
79292c56985d5d809f0dd6ca56afc4f7
|
cpp11_strongly_typed_enumerations
function newvalue = enumCheck(actual, expected)
if (actual != expected);
error("Enum value mismatch. Expected: %d Actual: %d", expected, actual);
endif
newvalue = expected + 1;
end
val = 0;
val = enumCheck(cpp11_strongly_typed_enumerations.Enum1_Val1, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum1_Val2, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum1_Val3, 13);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum1_Val4, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum1_Val5a, 13);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum1_Val6a, val);
val = 0;
val = enumCheck(cpp11_strongly_typed_enumerations.Enum2_Val1, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum2_Val2, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum2_Val3, 23);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum2_Val4, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum2_Val5b, 23);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum2_Val6b, val);
val = 0;
val = enumCheck(cpp11_strongly_typed_enumerations.Val1, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Val2, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Val3, 43);
val = enumCheck(cpp11_strongly_typed_enumerations.Val4, val);
val = 0;
val = enumCheck(cpp11_strongly_typed_enumerations.Enum5_Val1, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum5_Val2, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum5_Val3, 53);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum5_Val4, val);
val = 0;
val = enumCheck(cpp11_strongly_typed_enumerations.Enum6_Val1, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum6_Val2, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum6_Val3, 63);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum6_Val4, val);
val = 0;
val = enumCheck(cpp11_strongly_typed_enumerations.Enum7td_Val1, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum7td_Val2, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum7td_Val3, 73);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum7td_Val4, val);
val = 0;
val = enumCheck(cpp11_strongly_typed_enumerations.Enum8_Val1, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum8_Val2, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum8_Val3, 83);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum8_Val4, val);
val = 0;
val = enumCheck(cpp11_strongly_typed_enumerations.Enum10_Val1, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum10_Val2, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum10_Val3, 103);
val = enumCheck(cpp11_strongly_typed_enumerations.Enum10_Val4, val);
val = 0;
val = enumCheck(cpp11_strongly_typed_enumerations.Class1_Enum12_Val1, 1121);
val = enumCheck(cpp11_strongly_typed_enumerations.Class1_Enum12_Val2, 1122);
val = enumCheck(cpp11_strongly_typed_enumerations.Class1_Enum12_Val3, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Class1_Enum12_Val4, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Class1_Enum12_Val5c, 1121);
val = enumCheck(cpp11_strongly_typed_enumerations.Class1_Enum12_Val6c, val);
val = 0;
val = enumCheck(cpp11_strongly_typed_enumerations.Class1_Val1, 1131);
val = enumCheck(cpp11_strongly_typed_enumerations.Class1_Val2, 1132);
val = enumCheck(cpp11_strongly_typed_enumerations.Class1_Val3, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Class1_Val4, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Class1_Val5d, 1131);
val = enumCheck(cpp11_strongly_typed_enumerations.Class1_Val6d, val);
val = 0;
val = enumCheck(cpp11_strongly_typed_enumerations.Class1_Enum14_Val1, 1141);
val = enumCheck(cpp11_strongly_typed_enumerations.Class1_Enum14_Val2, 1142);
val = enumCheck(cpp11_strongly_typed_enumerations.Class1_Enum14_Val3, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Class1_Enum14_Val4, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Class1_Enum14_Val5e, 1141);
val = enumCheck(cpp11_strongly_typed_enumerations.Class1_Enum14_Val6e, val);
# Requires nested class support to work
#val = 0;
#val = enumCheck(cpp11_strongly_typed_enumerations.Class1_Struct1.Enum12_Val1, 3121);
#val = enumCheck(cpp11_strongly_typed_enumerations.Class1_Struct1.Enum12_Val2, 3122);
#val = enumCheck(cpp11_strongly_typed_enumerations.Class1_Struct1.Enum12_Val3, val);
#val = enumCheck(cpp11_strongly_typed_enumerations.Class1_Struct1.Enum12_Val4, val);
#val = enumCheck(cpp11_strongly_typed_enumerations.Class1_Struct1.Enum12_Val5f, 3121);
#val = enumCheck(cpp11_strongly_typed_enumerations.Class1_Struct1.Enum12_Val6f, val);
#
#val = 0;
#val = enumCheck(cpp11_strongly_typed_enumerations.Class1_Struct1.Val1, 3131);
#val = enumCheck(cpp11_strongly_typed_enumerations.Class1_Struct1.Val2, 3132);
#val = enumCheck(cpp11_strongly_typed_enumerations.Class1_Struct1.Val3, val);
#val = enumCheck(cpp11_strongly_typed_enumerations.Class1_Struct1.Val4, val);
#
#val = 0;
#val = enumCheck(cpp11_strongly_typed_enumerations.Class1_Struct1.Enum14_Val1, 3141);
#val = enumCheck(cpp11_strongly_typed_enumerations.Class1_Struct1.Enum14_Val2, 3142);
#val = enumCheck(cpp11_strongly_typed_enumerations.Class1_Struct1.Enum14_Val3, val);
#val = enumCheck(cpp11_strongly_typed_enumerations.Class1_Struct1.Enum14_Val4, val);
#val = enumCheck(cpp11_strongly_typed_enumerations.Class1_Struct1.Enum14_Val5g, 3141);
#val = enumCheck(cpp11_strongly_typed_enumerations.Class1_Struct1.Enum14_Val6g, val);
val = 0;
val = enumCheck(cpp11_strongly_typed_enumerations.Class2_Enum12_Val1, 2121);
val = enumCheck(cpp11_strongly_typed_enumerations.Class2_Enum12_Val2, 2122);
val = enumCheck(cpp11_strongly_typed_enumerations.Class2_Enum12_Val3, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Class2_Enum12_Val4, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Class2_Enum12_Val5h, 2121);
val = enumCheck(cpp11_strongly_typed_enumerations.Class2_Enum12_Val6h, val);
val = 0;
val = enumCheck(cpp11_strongly_typed_enumerations.Class2_Val1, 2131);
val = enumCheck(cpp11_strongly_typed_enumerations.Class2_Val2, 2132);
val = enumCheck(cpp11_strongly_typed_enumerations.Class2_Val3, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Class2_Val4, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Class2_Val5i, 2131);
val = enumCheck(cpp11_strongly_typed_enumerations.Class2_Val6i, val);
val = 0;
val = enumCheck(cpp11_strongly_typed_enumerations.Class2_Enum14_Val1, 2141);
val = enumCheck(cpp11_strongly_typed_enumerations.Class2_Enum14_Val2, 2142);
val = enumCheck(cpp11_strongly_typed_enumerations.Class2_Enum14_Val3, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Class2_Enum14_Val4, val);
val = enumCheck(cpp11_strongly_typed_enumerations.Class2_Enum14_Val5j, 2141);
val = enumCheck(cpp11_strongly_typed_enumerations.Class2_Enum14_Val6j, val);
# Requires nested class support to work
#val = 0;
#val = enumCheck(cpp11_strongly_typed_enumerations.Class2_Struct1_Enum12_Val1, 4121);
#val = enumCheck(cpp11_strongly_typed_enumerations.Class2_Struct1_Enum12_Val2, 4122);
#val = enumCheck(cpp11_strongly_typed_enumerations.Class2_Struct1_Enum12_Val3, val);
#val = enumCheck(cpp11_strongly_typed_enumerations.Class2_Struct1_Enum12_Val4, val);
#val = enumCheck(cpp11_strongly_typed_enumerations.Class2_Struct1_Enum12_Val5k, 4121);
#val = enumCheck(cpp11_strongly_typed_enumerations.Class2_Struct1_Enum12_Val6k, val);
#
#val = 0;
#val = enumCheck(cpp11_strongly_typed_enumerations.Class2_Struct1_Val1, 4131);
#val = enumCheck(cpp11_strongly_typed_enumerations.Class2_Struct1_Val2, 4132);
#val = enumCheck(cpp11_strongly_typed_enumerations.Class2_Struct1_Val3, val);
#val = enumCheck(cpp11_strongly_typed_enumerations.Class2_Struct1_Val4, val);
#val = enumCheck(cpp11_strongly_typed_enumerations.Class2_Struct1_Val5l, 4131);
#val = enumCheck(cpp11_strongly_typed_enumerations.Class2_Struct1_Val6l, val);
#
#val = 0;
#val = enumCheck(cpp11_strongly_typed_enumerations.Class2_Struct1_Enum14_Val1, 4141);
#val = enumCheck(cpp11_strongly_typed_enumerations.Class2_Struct1_Enum14_Val2, 4142);
#val = enumCheck(cpp11_strongly_typed_enumerations.Class2_Struct1_Enum14_Val3, val);
#val = enumCheck(cpp11_strongly_typed_enumerations.Class2_Struct1_Enum14_Val4, val);
#val = enumCheck(cpp11_strongly_typed_enumerations.Class2_Struct1_Enum14_Val5m, 4141);
#val = enumCheck(cpp11_strongly_typed_enumerations.Class2_Struct1_Enum14_Val6m, val);
class1 = Class1();
enumCheck(class1.class1Test1(cpp11_strongly_typed_enumerations.Enum1_Val5a), 13);
enumCheck(class1.class1Test2(cpp11_strongly_typed_enumerations.Class1_Enum12_Val5c), 1121);
#enumCheck(class1.class1Test3(cpp11_strongly_typed_enumerations.Class1_Struct1_Enum12_Val5f), 3121);
enumCheck(cpp11_strongly_typed_enumerations.globalTest1(cpp11_strongly_typed_enumerations.Enum1_Val5a), 13);
enumCheck(cpp11_strongly_typed_enumerations.globalTest2(cpp11_strongly_typed_enumerations.Class1_Enum12_Val5c), 1121);
#enumCheck(globalTest3(cpp11_strongly_typed_enumerations.Class1_Struct1_Enum12_Val5f), 3121);
|
github
|
medooze/swig-master
|
li_std_vector_enum_runme.m
|
.m
|
swig-master/Examples/test-suite/octave/li_std_vector_enum_runme.m
| 486 |
utf_8
|
486e8f0461a50153147831e1a8ada0f5
|
# do not dump Octave core
if exist("crash_dumps_octave_core", "builtin")
crash_dumps_octave_core(0);
endif
li_std_vector_enum
function check(a, b)
if (a != b)
error("incorrect match");
endif
end
ev = EnumVector();
check(ev.nums(0), 10);
check(ev.nums(1), 20);
check(ev.nums(2), 30);
it = ev.nums.begin();
v = it.value();
check(v, 10);
it.next();
v = it.value();
check(v, 20);
#expected = 10
#ev.nums.each do|val|
# swig_assert(val == expected)
# expected += 10
#end
|
github
|
medooze/swig-master
|
li_std_containers_overload_runme.m
|
.m
|
swig-master/Examples/test-suite/octave/li_std_containers_overload_runme.m
| 809 |
utf_8
|
b70b1cb696d6ff0fefe901c14415e676
|
# do not dump Octave core
if exist("crash_dumps_octave_core", "builtin")
crash_dumps_octave_core(0);
endif
li_std_containers_overload
function check(got, expected)
if (!strcmp(got, expected))
error("Failed check. '%s' != '%s'", got, expected)
endif
end
v = VectorX();
check(VectorOverload(v), "vector<X>");
v = VectorY();
check(VectorOverload(v), "vector<Y>");
v = VectorInt();
check(VectorOverload(v), "vector<int>");
v = VectorString();
check(VectorOverload(v), "vector<string>");
# TODO: Conversion from an Octave sequence not implemented yet
# v = {X()};
# check(VectorOverload(v), "vector<X>");
# v = {Y()};
# check(VectorOverload(v), "vector<Y>");
# v = {1, 2, 3};
# check(VectorOverload(v), "vector<int>");
# v = {"aaa", "bbb", "ccc"};
# check(VectorOverload(v), "vector<string>");
|
github
|
medooze/swig-master
|
exception_order_runme.m
|
.m
|
swig-master/Examples/test-suite/octave/exception_order_runme.m
| 1,008 |
utf_8
|
6133e2f0495da4196bfa27e670b12146
|
# do not dump Octave core
if exist("crash_dumps_octave_core", "builtin")
crash_dumps_octave_core(0);
endif
exception_order
function check_lasterror(expected)
if (!strcmp(lasterror.message, expected))
# Take account of older versions prefixing with "error: " and adding a newline at the end
if (!strcmp(regexprep(lasterror.message, 'error: (.*)\n$', '$1'), expected))
error(["Bad exception order. Expected: \"", expected, "\" Got: \"", lasterror.message, "\""])
endif
endif
endfunction
a = A();
try
a.foo()
catch
check_lasterror("C++ side threw an exception of type E1")
end_try_catch
try
a.bar()
catch
check_lasterror("C++ side threw an exception of type E2")
end_try_catch
try
a.foobar()
catch
check_lasterror("postcatch unknown (SWIG_RuntimeError)")
end_try_catch
try
a.barfoo(1)
catch
check_lasterror("C++ side threw an exception of type E1")
end_try_catch
try
a.barfoo(2)
catch
check_lasterror("C++ side threw an exception of type E2 *")
end_try_catch
|
github
|
medooze/swig-master
|
director_abstract_runme.m
|
.m
|
swig-master/Examples/test-suite/octave/director_abstract_runme.m
| 1,136 |
utf_8
|
1c206ea202edd1a1ecd87d4e23ff24d4
|
# do not dump Octave core
if exist("crash_dumps_octave_core", "builtin")
crash_dumps_octave_core(0);
endif
director_abstract
MyFoo=@() subclass(director_abstract.Foo(),@ping);
function out=ping(self)
out="MyFoo::ping()";
end
a = MyFoo();
if (!strcmp(a.ping(),"MyFoo::ping()"))
error(a.ping())
endif
if (!strcmp(a.pong(),"Foo::pong();MyFoo::ping()"))
error(a.pong())
endif
MyExample1=@() subclass(director_abstract.Example1(),'Color',@(self,r,g,b) r);
MyExample2=@(a,b) subclass(director_abstract.Example2(a,b),'Color',@(self,r,g,b) g);
MyExample3=@() subclass(director_abstract.Example3_i(),'Color',@(self,r,g,b) b);
me1 = MyExample1();
if (director_abstract.Example1.get_color(me1, 1,2,3) != 1)
error("failed");
endif
me2 = MyExample2(1,2);
if (me2.get_color(me2, 1,2,3) != 2)
error("failed");
endif
me3 = MyExample3();
if (me3.get_color(me3, 1,2,3) != 3)
error("failed");
endif
# don't check that we cannot construct abstract bases, since we have no
# way of disambiguating that with the normal construction case using
# subclass. furthermore, calling a pure virtual method will still generate
# an error.
|
github
|
medooze/swig-master
|
runme.m
|
.m
|
swig-master/Examples/octave/class/runme.m
| 1,110 |
utf_8
|
b64cce0a3528cfb71d766e399ec17646
|
# do not dump Octave core
if exist("crash_dumps_octave_core", "builtin")
crash_dumps_octave_core(0);
endif
# This file illustrates the proxy class C++ interface generated
# by SWIG.
swigexample
# ----- Object creation -----
printf("Creating some objects:\n");
c = swigexample.Circle(10)
s = swigexample.Square(10)
# ----- Access a static member -----
printf("\nA total of %i shapes were created\n", swigexample.Shape.nshapes);
# ----- Member data access -----
# Set the location of the object
c.x = 20
c.y = 30
s.x = -10
s.y = 5
printf("\nHere is their current position:\n");
printf(" Circle = (%f, %f)\n",c.x,c.y);
printf(" Square = (%f, %f)\n",s.x,s.y);
# ----- Call some methods -----
printf("\nHere are some properties of the shapes:\n");
function print_shape(o)
o
printf(" area = %f\n", o.area());
printf(" perimeter = %f\n", o.perimeter());
end;
print_shape(c);
print_shape(s);
printf("\nGuess I'll clean up now\n");
# Note: this invokes the virtual destructor
clear c
clear s
printf("%i shapes remain\n", swigexample.Shape.nshapes);
printf("Goodbye\n");
|
github
|
medooze/swig-master
|
horzcat.m
|
.m
|
swig-master/Examples/octave/operator/@swig_ref/horzcat.m
| 229 |
utf_8
|
40c402670369b6e777422cca21c0d567
|
% test octaves concatenation operator
function ret=horzcat(a, b)
% return the concatenation of two ComplexVal values as a cell array.
% (not really useful but it tests the concatenation of swig_ref objects)
ret={a, b};
end
|
github
|
medooze/swig-master
|
runme.m
|
.m
|
swig-master/Examples/octave/module_load/runme.m
| 2,491 |
utf_8
|
657725c3b1f299ed4a5a705cdfa3339c
|
# do not dump Octave core
if exist("crash_dumps_octave_core", "builtin")
crash_dumps_octave_core(0);
endif
# load module
clear all;
assert(exist("swigexample") == 3);
swigexample;
assert(isglobal("swigexample"));
assert(cvar.ivar == ifunc);
clear all
assert(exist("swigexample") == 3);
swigexample;
assert(isglobal("swigexample"));
assert(cvar.ivar == ifunc);
clear all
# load module in a function globally before base context
clear all;
function testme_1
% exist("swigexample") returns 1 (variable) in octave >= 4.4 < 6 but 3 (.oct file) in octave >= 6
assert(exist("swigexample"));
swigexample;
assert(isglobal("swigexample"));
assert(cvar.ivar == ifunc);
endfunction
testme_1
testme_1
assert(exist("swigexample") == 3);
swigexample;
assert(isglobal("swigexample"));
assert(cvar.ivar == ifunc);
clear all
function testme_2
% exist("swigexample") returns 1 (variable) in octave >= 4.4 < 6 but 3 (.oct file) in octave >= 6
assert(exist("swigexample"));
swigexample;
assert(isglobal("swigexample"));
assert(cvar.ivar == ifunc);
endfunction
testme_2
testme_2
assert(exist("swigexample") == 3);
swigexample;
assert(isglobal("swigexample"));
assert(cvar.ivar == ifunc);
clear all
# load module in a function globally after base context
clear all;
assert(exist("swigexample") == 3);
swigexample;
assert(isglobal("swigexample"));
assert(cvar.ivar == ifunc);
function testme_3
% exist("swigexample") returns 1 (variable) in octave >= 4.4 < 6 but 3 (.oct file) in octave >= 6
assert(exist("swigexample"));
swigexample;
assert(isglobal("swigexample"));
assert(cvar.ivar == ifunc);
endfunction
testme_3
testme_3
clear all
assert(exist("swigexample") == 3);
swigexample;
assert(isglobal("swigexample"));
assert(cvar.ivar == ifunc);
function testme_4
% exist("swigexample") returns 1 (variable) in octave >= 4.4 < 6 but 3 (.oct file) in octave >= 6
assert(exist("swigexample"));
swigexample;
assert(isglobal("swigexample"));
assert(cvar.ivar == ifunc);
endfunction
testme_4
testme_4
clear all
# octave 3.0.5 randomly crashes on the remaining tests
if !swig_octave_prereq(3,2,0)
exit
endif
# load module with no cvar
clear all;
who;
assert(exist("swigexample2") == 3);
swigexample2;
assert(isglobal("swigexample2"));
assert(swigexample2.ivar == ifunc);
assert(!exist("cvar", "var"));
clear all
assert(exist("swigexample2") == 3);
swigexample2;
assert(isglobal("swigexample2"));
assert(swigexample2.ivar == ifunc);
assert(!exist("cvar", "var"));
clear all
|
github
|
FelixPerezCicala/modRankineSCC-master
|
polyvaln.m
|
.m
|
modRankineSCC-master/01 Solver/01-02 Funciones/polyvaln.m
| 3,497 |
utf_8
|
fecc9f839aa56c6637fac3907f279e43
|
function y = polyvaln(p,x)
%POLYVALN evaluate a multivariate polynomial
%
% The n-variate polynomial p, represented as an n-dimensional
% array, is evaluated for each value in the array x. The last
% dimension of x should be of size n corresponding to the n
% variables in the polynomial.
%
% Following the convention used in polyval(), the highest
% order coefficient of the polynomial comes first in the
% array, and we take the first index to be the index of
% the x-coefficient, the second of the y-coefficient and
% so on. For a bivariate polynomial the array is a matrix
% and we have this sort of structure
%
% [ x^n y^m, x^n y^(m-1), ... x^n y, x^n
% x^(n-1) y^m, x^(n-1) y^(m-1), ... x^(n-1) y, x^(n-1)
% :
% x y^m, x y^(m-1), ... xy, x
% y^m, y^(m-1), ... y, 1]
%
% Example: the polynomial x^2 + 2y^2 - 1
%
% p = [0,0,1;
% 0,0,0;
% 2,0,-1]
%
% Evaluated at x=1, y=2
%
% polyvaln(p,[1,2])
% ans = 8
%
% Evaluated at x,y = 1,..,5: we generate a 5x5x2 array xy
% with the x values in xy(:,;,1), the y values in xy(:,:,2)
%
% [x,y] = meshgrid(1:5)
% xy = cat(3,x,y)
% polyvaln(p,xy)
% ans =
% 2 5 10 17 26
% 8 11 16 23 32
% 18 21 26 33 42
% 32 35 40 47 56
% 50 53 58 65 74
%
% The evaluation method is a nested Horner's rule which is
% implemented recursively. No attempt is made to exploit the
% sparsity (if any) of the polynomial.
%
% NOTE - this file should not be confused with the file of the
% same name included with the PolyFit package by John D'Errico
% http://mathworks.com/matlabcentral/fileexchange/34765-polyfitn
%
% Copyright (c) 2011, 2012, J.J. Green
% $Id: polyvaln.m,v 1.6 2012/05/15 20:26:02 jjg Exp $
%
% Changes
%
% 06 Jan 2011 : initial octave version
% 24 Jul 2011 : ported to work with matlab (7.12.0.635)
% 15 Mar 2012 : added note on the file in polyfit package
% check arguments
if nargin ~= 2
error('exactly 2 arguments required')
end
% handle trivial case
if isvector(p)
y = polyval(p,x);
return;
end
% size of last dimension of x
if isvector(x)
ndx = 1;
sldx = length(x);
else
dx = size(x);
ndx = numel(dx);
sldx = dx(ndx);
end
% number of dimensions of p
dp = size(p);
ndp = numel(dp);
% check dimensions match
if ndp ~= sldx
error('size of last dim of x should equal number of dims of p')
end
% reshape x if needed
if ndx > 1
x = reshape(x,prod(dx(1:ndx-1)),sldx);
end
% call recursive subfunction
y = pvn2(p,x);
% reshape y to the same pattern as x if needed
if ndx > 2
y = reshape(y,dx(1:ndx-1));
end
end
% recurse over the dimensions of p, evaluating using
% polyval() at the leaves of the recursion but pvn3()
% as we accumulate the totals
function y = pvn2(p,x)
if isvector(p)
y = polyval(p,x);
return
end
d = size(p);
nd = numel(d);
c(1:nd-1) = {':'};
x0 = x(:,2:nd);
for i = 1:d(1)
p0 = squeeze(p(i,c{:}));
p1(:,i) = pvn2(p0,x0);
end
y = pvn3(p1,x(:,1));
end
% this is like polyval() except that p is an matrix
% with the same number of rows as x
function y = pvn3(p,x)
n = size(p,2);
y = p(:,1);
for k = 2:n
y = y.*x + p(:,k);
end
end
|
github
|
chuangao/BicMix-master
|
KSVD.m
|
.m
|
BicMix-master/KSVD/KSVD.m
| 12,290 |
utf_8
|
6233b813f69dc0129006dd93929e3b99
|
function [Dictionary,output] = KSVD(...
Data,... % an nXN matrix that contins N signals (Y), each of dimension n.
param)
% =========================================================================
% K-SVD algorithm
% =========================================================================
% The K-SVD algorithm finds a dictionary for linear representation of
% signals. Given a set of signals, it searches for the best dictionary that
% can sparsely represent each signal. Detailed discussion on the algorithm
% and possible applications can be found in "The K-SVD: An Algorithm for
% Designing of Overcomplete Dictionaries for Sparse Representation", written
% by M. Aharon, M. Elad, and A.M. Bruckstein and appeared in the IEEE Trans.
% On Signal Processing, Vol. 54, no. 11, pp. 4311-4322, November 2006.
% =========================================================================
% INPUT ARGUMENTS:
% Data an nXN matrix that contins N signals (Y), each of dimension n.
% param structure that includes all required
% parameters for the K-SVD execution.
% Required fields are:
% K, ... the number of dictionary elements to train
% numIteration,... number of iterations to perform.
% errorFlag... if =0, a fix number of coefficients is
% used for representation of each signal. If so, param.L must be
% specified as the number of representing atom. if =1, arbitrary number
% of atoms represent each signal, until a specific representation error
% is reached. If so, param.errorGoal must be specified as the allowed
% error.
% preserveDCAtom... if =1 then the first atom in the dictionary
% is set to be constant, and does not ever change. This
% might be useful for working with natural
% images (in this case, only param.K-1
% atoms are trained).
% (optional, see errorFlag) L,... % maximum coefficients to use in OMP coefficient calculations.
% (optional, see errorFlag) errorGoal, ... % allowed representation error in representing each signal.
% InitializationMethod,... mehtod to initialize the dictionary, can
% be one of the following arguments:
% * 'DataElements' (initialization by the signals themselves), or:
% * 'GivenMatrix' (initialization by a given matrix param.initialDictionary).
% (optional, see InitializationMethod) initialDictionary,... % if the initialization method
% is 'GivenMatrix', this is the matrix that will be used.
% (optional) TrueDictionary, ... % if specified, in each
% iteration the difference between this dictionary and the trained one
% is measured and displayed.
% displayProgress, ... if =1 progress information is displyed. If param.errorFlag==0,
% the average repersentation error (RMSE) is displayed, while if
% param.errorFlag==1, the average number of required coefficients for
% representation of each signal is displayed.
% =========================================================================
% OUTPUT ARGUMENTS:
% Dictionary The extracted dictionary of size nX(param.K).
% output Struct that contains information about the current run. It may include the following fields:
% CoefMatrix The final coefficients matrix (it should hold that Data equals approximately Dictionary*output.CoefMatrix.
% ratio If the true dictionary was defined (in
% synthetic experiments), this parameter holds a vector of length
% param.numIteration that includes the detection ratios in each
% iteration).
% totalerr The total representation error after each
% iteration (defined only if
% param.displayProgress=1 and
% param.errorFlag = 0)
% numCoef A vector of length param.numIteration that
% include the average number of coefficients required for representation
% of each signal (in each iteration) (defined only if
% param.displayProgress=1 and
% param.errorFlag = 1)
% =========================================================================
if (~isfield(param,'displayProgress'))
param.displayProgress = 0;
end
totalerr(1) = 99999;
if (isfield(param,'errorFlag')==0)
param.errorFlag = 0;
end
if (isfield(param,'TrueDictionary'))
displayErrorWithTrueDictionary = 1;
ErrorBetweenDictionaries = zeros(param.numIteration+1,1);
ratio = zeros(param.numIteration+1,1);
else
displayErrorWithTrueDictionary = 0;
ratio = 0;
end
if (param.preserveDCAtom>0)
FixedDictionaryElement(1:size(Data,1),1) = 1/sqrt(size(Data,1));
else
FixedDictionaryElement = [];
end
% coefficient calculation method is OMP with fixed number of coefficients
if (size(Data,2) < param.K)
disp('Size of data is smaller than the dictionary size. Trivial solution...');
Dictionary = Data(:,1:size(Data,2));
return;
elseif (strcmp(param.InitializationMethod,'DataElements'))
Dictionary(:,1:param.K-param.preserveDCAtom) = Data(:,1:param.K-param.preserveDCAtom);
elseif (strcmp(param.InitializationMethod,'GivenMatrix'))
Dictionary(:,1:param.K-param.preserveDCAtom) = param.initialDictionary(:,1:param.K-param.preserveDCAtom);
end
% reduce the components in Dictionary that are spanned by the fixed
% elements
if (param.preserveDCAtom)
tmpMat = FixedDictionaryElement \ Dictionary;
Dictionary = Dictionary - FixedDictionaryElement*tmpMat;
end
%normalize the dictionary.
Dictionary = Dictionary*diag(1./sqrt(sum(Dictionary.*Dictionary)));
Dictionary = Dictionary.*repmat(sign(Dictionary(1,:)),size(Dictionary,1),1); % multiply in the sign of the first element.
totalErr = zeros(1,param.numIteration);
% the K-SVD algorithm starts here.
for iterNum = 1:param.numIteration
% find the coefficients
if (param.errorFlag==0)
%CoefMatrix = mexOMPIterative2(Data, [FixedDictionaryElement,Dictionary],param.L);
CoefMatrix = OMP([FixedDictionaryElement,Dictionary],Data, param.L);
else
%CoefMatrix = mexOMPerrIterative(Data, [FixedDictionaryElement,Dictionary],param.errorGoal);
CoefMatrix = OMPerr([FixedDictionaryElement,Dictionary],Data, param.errorGoal);
param.L = 1;
end
replacedVectorCounter = 0;
rPerm = randperm(size(Dictionary,2));
for j = rPerm
[betterDictionaryElement,CoefMatrix,addedNewVector] = I_findBetterDictionaryElement(Data,...
[FixedDictionaryElement,Dictionary],j+size(FixedDictionaryElement,2),...
CoefMatrix ,param.L);
Dictionary(:,j) = betterDictionaryElement;
if (param.preserveDCAtom)
tmpCoef = FixedDictionaryElement\betterDictionaryElement;
Dictionary(:,j) = betterDictionaryElement - FixedDictionaryElement*tmpCoef;
Dictionary(:,j) = Dictionary(:,j)./sqrt(Dictionary(:,j)'*Dictionary(:,j));
end
replacedVectorCounter = replacedVectorCounter+addedNewVector;
end
if (iterNum>1 & param.displayProgress)
if (param.errorFlag==0)
output.totalerr(iterNum-1) = sqrt(sum(sum((Data-[FixedDictionaryElement,Dictionary]*CoefMatrix).^2))/prod(size(Data)));
disp(['Iteration ',num2str(iterNum),' Total error is: ',num2str(output.totalerr(iterNum-1))]);
else
output.numCoef(iterNum-1) = length(find(CoefMatrix))/size(Data,2);
disp(['Iteration ',num2str(iterNum),' Average number of coefficients: ',num2str(output.numCoef(iterNum-1))]);
end
end
if (displayErrorWithTrueDictionary )
[ratio(iterNum+1),ErrorBetweenDictionaries(iterNum+1)] = I_findDistanseBetweenDictionaries(param.TrueDictionary,Dictionary);
disp(strcat(['Iteration ', num2str(iterNum),' ratio of restored elements: ',num2str(ratio(iterNum+1))]));
output.ratio = ratio;
end
Dictionary = I_clearDictionary(Dictionary,CoefMatrix(size(FixedDictionaryElement,2)+1:end,:),Data);
if (isfield(param,'waitBarHandle'))
waitbar(iterNum/param.counterForWaitBar);
end
end
output.CoefMatrix = CoefMatrix;
Dictionary = [FixedDictionaryElement,Dictionary];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% findBetterDictionaryElement
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [betterDictionaryElement,CoefMatrix,NewVectorAdded] = I_findBetterDictionaryElement(Data,Dictionary,j,CoefMatrix,numCoefUsed)
if (length(who('numCoefUsed'))==0)
numCoefUsed = 1;
end
relevantDataIndices = find(CoefMatrix(j,:)); % the data indices that uses the j'th dictionary element.
if (length(relevantDataIndices)<1) %(length(relevantDataIndices)==0)
ErrorMat = Data-Dictionary*CoefMatrix;
ErrorNormVec = sum(ErrorMat.^2);
[d,i] = max(ErrorNormVec);
betterDictionaryElement = Data(:,i);%ErrorMat(:,i); %
betterDictionaryElement = betterDictionaryElement./sqrt(betterDictionaryElement'*betterDictionaryElement);
betterDictionaryElement = betterDictionaryElement.*sign(betterDictionaryElement(1));
CoefMatrix(j,:) = 0;
NewVectorAdded = 1;
return;
end
NewVectorAdded = 0;
tmpCoefMatrix = CoefMatrix(:,relevantDataIndices);
tmpCoefMatrix(j,:) = 0;% the coeffitients of the element we now improve are not relevant.
errors =(Data(:,relevantDataIndices) - Dictionary*tmpCoefMatrix); % vector of errors that we want to minimize with the new element
% % the better dictionary element and the values of beta are found using svd.
% % This is because we would like to minimize || errors - beta*element ||_F^2.
% % that is, to approximate the matrix 'errors' with a one-rank matrix. This
% % is done using the largest singular value.
[betterDictionaryElement,singularValue,betaVector] = svds(errors,1);
CoefMatrix(j,relevantDataIndices) = singularValue*betaVector';% *signOfFirstElem
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% findDistanseBetweenDictionaries
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [ratio,totalDistances] = I_findDistanseBetweenDictionaries(original,new)
% first, all the column in oiginal starts with positive values.
catchCounter = 0;
totalDistances = 0;
for i = 1:size(new,2)
new(:,i) = sign(new(1,i))*new(:,i);
end
for i = 1:size(original,2)
d = sign(original(1,i))*original(:,i);
distances =sum ( (new-repmat(d,1,size(new,2))).^2);
[minValue,index] = min(distances);
errorOfElement = 1-abs(new(:,index)'*d);
totalDistances = totalDistances+errorOfElement;
catchCounter = catchCounter+(errorOfElement<0.01);
end
ratio = 100*catchCounter/size(original,2);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% I_clearDictionary
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Dictionary = I_clearDictionary(Dictionary,CoefMatrix,Data)
T2 = 0.99;
T1 = 3;
K=size(Dictionary,2);
Er=sum((Data-Dictionary*CoefMatrix).^2,1); % remove identical atoms
G=Dictionary'*Dictionary; G = G-diag(diag(G));
for jj=1:1:K,
if max(G(jj,:))>T2 | length(find(abs(CoefMatrix(jj,:))>1e-7))<=T1 ,
[val,pos]=max(Er);
Er(pos(1))=0;
Dictionary(:,jj)=Data(:,pos(1))/norm(Data(:,pos(1)));
G=Dictionary'*Dictionary; G = G-diag(diag(G));
end;
end;
|
github
|
chuangao/BicMix-master
|
KSVD_NN.m
|
.m
|
BicMix-master/KSVD/KSVD_NN.m
| 11,585 |
utf_8
|
c538d2b9c08c765e3fef74f474236041
|
function [Dictionary,output] = KSVD_NN(...
Data,... % an nXN matrix that contins N signals (Y), each of dimension n.
param)
% =========================================================================
% Non Negative K-SVD algorithm
% =========================================================================
% The NN-K-SVD algorithm finds a non-negative dictionary for linear representation of
% signals. Given a set of signals, it searches for the best dictionary that
% can sparsely represent each signal. Detailed discussion on the algorithm
% and possible applications can be found in "K-SVD and its non-negative
% variant for dictionary design", written by M. Aharon, M. Elad, and A.M. Bruckstein
% and appeared in the Proceedings of the SPIE conference wavelets, Vol.
% 5914, July 2005.
% =========================================================================
% INPUT ARGUMENTS:
% Data an nXN matrix that contins N signals (Y), each of dimension n.
% param structure that includes all required
% parameters for the K-SVD execution.
% Required fields are:
% K, ... the number of dictionary elements to train
% numIteration,... number of iterations to perform.
% L,... maximum coefficients to use in OMP coefficient calculations.
% InitializationMethod,... mehtod to initialize the dictionary, can
% be one of the following arguments:
% * 'DataElements' (initialization by the signals themselves), or:
% * 'GivenMatrix' (initialization by a given matrix param.initialDictionary).
% (optional, see InitializationMethod) initialDictionary,... % if the initialization method
% is 'GivenMatrix', this is the matrix that will be used.
% (optional) TrueDictionary, ... % if specified, in each
% iteration the difference between this dictionary and the trained one
% is measured and displayed.
% displayProgress, ... if =1 progress information is displyed. If param.errorFlag==0,
% the average repersentation error (RMSE) is displayed, while if
% param.errorFlag==1, the average number of required coefficients for
% representation of each signal is displayed.
% =========================================================================
% OUTPUT ARGUMENTS:
% Dictionary The extracted dictionary of size nX(param.K).
% output Struct that contains information about the current run. It may include the following fields:
% CoefMatrix The final coefficients matrix (it should hold that Data equals approximately Dictionary*output.CoefMatrix.
% ratio If the true dictionary was defined (in
% synthetic experiments), this parameter holds a vector of length
% param.numIteration that includes the detection ratios in each
% iteration).
% totalerr The total representation error after each
% iteration (defined only if
% param.displayProgress=1)
% =========================================================================
if (~isfield(param,'displayProgress'))
param.displayProgress = 0;
end
totalerr(1) = 99999;
if (isfield(param,'errorFlag')==0)
param.errorFlag = 0;
end
%Data(Data<0) = 0;
if (isfield(param,'TrueDictionary'))
displayErrorWithTrueDictionary = 1;
ErrorBetweenDictionaries = zeros(param.numIteration+1,1);
ratio = zeros(param.numIteration+1,1);
else
displayErrorWithTrueDictionary = 0;
ratio = 0;
end
if (param.preserveDCAtom>0)
FixedDictionaryElement(:,1) = 1/sqrt(size(Data,1));
else
FixedDictionaryElement = [];
end
% coefficient calculation method is OMP with fixed number of coefficients
if (size(Data,2) < param.K)
disp('Size of data is smaller than the dictionary size. Trivial solution...');
Dictionary = Data(:,1:size(Data,2));
return;
elseif (strcmp(param.InitializationMethod,'DataElements'))
Dictionary(:,1:param.K) = Data(:,1:param.K-param.preserveDCAtom);
elseif (strcmp(param.InitializationMethod,'GivenMatrix'))
Dictionary = param.initialDictionary(:,1:param.K-param.preserveDCAtom);
end
% reduce the components in Dictionary that are spanned by the fixed
% elements
if (param.preserveDCAtom)
tmpMat = FixedDictionaryElement \ Dictionary;
Dictionary = Dictionary - FixedDictionaryElement*tmpMat;
end
%normalize the dictionary.
Dictionary = Dictionary*diag(1./sqrt(sum(Dictionary.*Dictionary)));
totalErr = zeros(1,param.numIteration);
CoefMatrix = sparse(param.K,size(Data,2));
% the K-SVD algorithm starts here.
for iterNum = 1:param.numIteration
% find the coefficients
CoefMatrix = NN_BP(Data, [FixedDictionaryElement,Dictionary],param.L,CoefMatrix);
replacedVectorCounter = 0;
rPerm = randperm(size(Dictionary,2));
for j = rPerm
[betterDictionaryElement,CoefMatrix,addedNewVector] = I_findBetterDictionaryElement(Data,...
[FixedDictionaryElement,Dictionary],j+size(FixedDictionaryElement,2),...
CoefMatrix ,param.L);
Dictionary(:,j) = betterDictionaryElement;
if (param.preserveDCAtom)
tmpCoef = FixedDictionaryElement\betterDictionaryElement;
Dictionary(:,j) = betterDictionaryElement - FixedDictionaryElement*tmpCoef;
Dictionary(:,j) = Dictionary(:,j)./sqrt(Dictionary(:,j)'*Dictionary(:,j));
end
replacedVectorCounter = replacedVectorCounter+addedNewVector;
end
if (iterNum>1 & param.displayProgress)
if (param.errorFlag==0)
output.totalerr(iterNum-1) = sqrt(sum(sum((Data-[FixedDictionaryElement,Dictionary]*CoefMatrix).^2))/prod(size(Data)));
disp(['Iteration ',num2str(iterNum),' Total error is: ',num2str(output.totalerr(iterNum-1))]);
else
output.numCoef(iterNum-1) = length(find(CoefMatrix))/size(Data,2);
disp(['Iteration ',num2str(iterNum),' Average number of coefficients: ',num2str(output.numCoef(iterNum-1))]);
end
end
if (displayErrorWithTrueDictionary )
[ratio(iterNum+1),ErrorBetweenDictionaries(iterNum+1)] = I_findDistanseBetweenDictionaries(param.TrueDictionary,Dictionary);
disp(strcat(['Iteration ', num2str(iterNum),' ratio of restored elements: ',num2str(ratio(iterNum+1))]));
output.ratio = ratio;
end
Dictionary = I_clearDictionary(Dictionary,CoefMatrix,Data);
if (isfield(param,'waitBarHandle'))
waitbar(iterNum/param.counterForWaitBar);
end
end
output.CoefMatrix = CoefMatrix;
Dictionary = [FixedDictionaryElement,Dictionary];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% findBetterDictionaryElement
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [betterDictionaryElement,CoefMatrix,NewVectorAdded] = I_findBetterDictionaryElement(Data,Dictionary,j,CoefMatrix,numCoefUsed)
if (length(who('numCoefUsed'))==0)
numCoefUsed = 1;
end
relevantDataIndices = find(CoefMatrix(j,:)); % the data indices that uses the j'th dictionary element.
if (length(relevantDataIndices)<1) %(length(relevantDataIndices)==0)
ErrorMat = Data-Dictionary*CoefMatrix;
ErrorNormVec = sum(ErrorMat.^2);
[d,i] = max(ErrorNormVec);
betterDictionaryElement = Data(:,i);%ErrorMat(:,i); %
betterDictionaryElement = betterDictionaryElement./sqrt(betterDictionaryElement'*betterDictionaryElement);
betterDictionaryElement = betterDictionaryElement.*sign(betterDictionaryElement(1));
CoefMatrix(j,:) = 0;
NewVectorAdded = 1;
return;
end
NewVectorAdded = 0;
reduced_coeff = CoefMatrix(:, relevantDataIndices);
reduced_Data = Data (:, relevantDataIndices);
saveDebugDict = Dictionary(:,j);
saveDebugCoef = reduced_coeff(j,:);
%debug1 = sum(sum((reduced_Data - Dictionary*reduced_coeff).^2));
reduced_coeff (j, :) = 0; % all but the j-th element
err_mat = reduced_Data - Dictionary * reduced_coeff;
[U S V flag] = svds((err_mat), 1);
% check for sign, flip U and V's sign if negative.
Idx_U = find(U<0);
Idx_V = find(V<0);
u1 = U; u1(Idx_U) = 0; v1 = V; v1(Idx_V) = 0;approx1 = norm(err_mat- u1*v1'*S);
u1 = zeros(size(U)); u1(Idx_U) = -U(Idx_U); v1 = zeros(size(V)); v1(Idx_V) = -V(Idx_V);approx2 = norm(err_mat- u1*v1'*S);
if (approx1<= approx2)
betterDictionaryElement = U;
betterDictionaryElement(Idx_U) = 0;
coefs = V;
coefs(Idx_V) = 0;
else
betterDictionaryElement = zeros(size(U));
betterDictionaryElement(Idx_U) = -U(Idx_U);
coefs = zeros(size(V));
coefs(Idx_V) = -V(Idx_V);
end
newAtomNorm = sqrt(betterDictionaryElement'*betterDictionaryElement);
betterDictionaryElement = betterDictionaryElement/newAtomNorm;
coefs = coefs * newAtomNorm;
% coefs(coefs<0) = 0;
newE = sum(sum(((reduced_Data - Dictionary(:,[1:j-1,j+1:end])*reduced_coeff([1:j-1,j+1:end],:))-betterDictionaryElement*coefs').^2));
oldE = sum(sum(((reduced_Data - Dictionary(:,[1:j-1,j+1:end])*reduced_coeff([1:j-1,j+1:end],:))-saveDebugDict*saveDebugCoef).^2));
if (newE>oldE)
for iter = 1:30 % the number of iterations
betterDictionaryElement = err_mat*coefs/(coefs'*coefs);
betterDictionaryElement(betterDictionaryElement<0) = 0;
coefs = err_mat'*betterDictionaryElement/(betterDictionaryElement'*betterDictionaryElement);
coefs(coefs<0) = 0;
end
newAtomNorm = sqrt(betterDictionaryElement'*betterDictionaryElement);
betterDictionaryElement = betterDictionaryElement/newAtomNorm;
coefs = coefs * newAtomNorm;
reduced_coeff(j,:) = coefs;
end
reduced_coeff(j,:) = coefs;
CoefMatrix (:, relevantDataIndices) =reduced_coeff;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% findDistanseBetweenDictionaries
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [ratio,totalDistances] = I_findDistanseBetweenDictionaries(original,new)
% first, all the column in oiginal starts with positive values.
catchCounter = 0;
totalDistances = 0;
for i = 1:size(new,2)
new(:,i) = new(:,i);
end
for i = 1:size(original,2)
d = original(:,i);
distances =sum ( (new-repmat(d,1,size(new,2))).^2);
[minValue,index] = min(distances);
errorOfElement = 1-abs(new(:,index)'*d);
totalDistances = totalDistances+errorOfElement;
catchCounter = catchCounter+(errorOfElement<0.01);
end
ratio = 100*catchCounter/size(original,2);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% I_clearDictionary
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Dictionary = I_clearDictionary(Dictionary,CoefMatrix,Data)
T2 = 0.999;
T1 = 3;
K=size(Dictionary,2);
Er=sum((Data-Dictionary*CoefMatrix).^2,1); % remove identical atoms
G=Dictionary'*Dictionary; G = G-diag(diag(G));
for jj=1:1:K,
if max(G(jj,:))>T2 | length(find(abs(CoefMatrix(jj,:))>1e-7))<=T1 ,
[val,pos]=max(Er);
Er(pos(1))=0;
Dictionary(:,jj)=Data(:,pos(1))/norm(Data(:,pos(1)));
G=Dictionary'*Dictionary; G = G-diag(diag(G));
end;
end;
|
github
|
chuangao/BicMix-master
|
gererateSyntheticDictionaryAndData.m
|
.m
|
BicMix-master/KSVD/gererateSyntheticDictionaryAndData.m
| 1,896 |
utf_8
|
16de7e46c7a20f0172cc50b3ec4ea1c7
|
function [Dictionary, data, coefs] = gererateSyntheticDictionaryAndData(N, L, dim, K, SNRdB)
randn('state',sum(100*clock));
rand('state',sum(100*clock));
Dictionary = randn(dim,K);
Dictionary = Dictionary*diag(1./sqrt(sum(Dictionary.*Dictionary)));
[data,coefs] = CreateDataFromDictionarySimple(Dictionary, N, L);
if (SNRdB==0) | (SNRdB == 80)
return
else
noise = randn(size(data));
actualNoise = calcNoiseFromSNR(SNRdB,data, noise);
SNR = calcSNR(data, data+actualNoise);
data = data + actualNoise*SNR/SNRdB;
end
function [D,xOrig] = CreateDataFromDictionarySimple(dictionary, numElements, numCoef)
maxRangeOfCoef = 1;
resolution = 0.0001;
xOrig = zeros(size(dictionary,2),numElements);
%vecOfValues = -1*maxRangeOfCoef:resolution:maxRangeOfCoef;
%coefs = randsrc(numCoef,numElements,vecOfValues);
coefs = randn(numCoef,numElements)*maxRangeOfCoef;
xOrig(1:numCoef,:) = coefs;
for i=1:size(xOrig,2)
xOrig(:,i) = xOrig(randperm(size(xOrig,1)),i);
end
%dictionaryElementIndices = randsrc(numCoef*numElements,1,[1:size(dictionary,2)]) ;
%matrixOfIndices = repmat([1:numElements],numCoef,1);
%xOrig(sub2ind(size(xOrig),dictionaryElementIndices,matrixOfIndices(:))) = coefs;
D = dictionary*xOrig;
function actualNoise = calcNoiseFromSNR(TargerSNR, signal, randomNoise)
signal = signal(:);
randomNoiseRow = randomNoise(:);
signal_2 = sum(signal.^2);
ActualNoise_2 = signal_2/(10^(TargerSNR/10));
noise_2 = sum(randomNoiseRow.^2);
ratio = ActualNoise_2./noise_2;
actualNoise = randomNoiseRow.*repmat(sqrt(ratio),size(randomNoiseRow,1),1);
actualNoise = reshape(actualNoise,size(randomNoise));
function SNR = calcSNR(origSignal, noisySignal)
errorSignal = origSignal-noisySignal;
signal_2 = sum(origSignal.^2);
noise_2 = sum(errorSignal.^2);
SNRValues = 10*log10(signal_2./noise_2);
SNR = mean(SNRValues);
|
github
|
chuangao/BicMix-master
|
demo3.m
|
.m
|
BicMix-master/KSVD/demo3.m
| 8,504 |
utf_8
|
1813214e07f98c446ffd04b272843686
|
function demo3()
% NN-KSVD running file - a synthetic test.
% in this file a synthetic test of the NN-K-SVD (non-negative K-SVD)
% algorithm is performed. This exact Test is presented in "K-SVD and its non-negative
% variant for dictionary design", written by M. Aharon, M. Elad, and A.M. Bruckstein
% and appeared in the Proceedings of the SPIE conference wavelets, Vol.
% 5914, July 2005.
param.K = 10*9;
param.L = 5;
SNR = 20;
numRequiredPoints = 2000;
sizeOfElem = 64;
A = zeros(sizeOfElem,90);
param.numIteration = 200;
param.initialDictionary = rand(sizeOfElem,param.K);
param.InitializationMethod = 'GivenMatrix';
% =================================
% end of parameter setting
% =================================
basisFunction{1} = [0 0 0 0 0 0 0 0 ;
0 0 0 1 1 0 0 0 ;
0 0 1 0 1 0 0 0;
0 0 1 0 1 0 0 0;
0 0 0 0 1 0 0 0 ;
0 0 0 0 1 0 0 0 ;
0 0 0 0 1 0 0 0 ;
0 0 0 0 0 0 0 0 ];
basisFunction{2} = [0 0 0 0 0 0 0 0 ;
0 0 1 1 1 1 0 0 ;
0 0 1 0 0 1 0 0;
0 0 0 0 1 1 0 0;
0 0 0 1 1 0 0 0 ;
0 0 1 1 0 0 0 0 ;
0 0 1 1 1 1 0 0 ;
0 0 0 0 0 0 0 0 ];
basisFunction{3} = [0 0 0 0 0 0 0 0 ;
0 0 1 1 1 1 0 0 ;
0 0 0 0 1 1 0 0;
0 0 0 1 1 0 0 0;
0 0 0 0 1 1 0 0 ;
0 0 0 0 0 1 0 0 ;
0 0 1 1 1 1 0 0 ;
0 0 0 0 0 0 0 0 ];
basisFunction{4} = [0 0 0 0 0 0 0 0 ;
0 0 1 0 0 1 0 0 ;
0 0 1 0 0 1 0 0;
0 0 1 0 0 1 0 0;
0 0 1 1 1 1 0 0 ;
0 0 0 0 0 1 0 0 ;
0 0 0 0 0 1 0 0 ;
0 0 0 0 0 0 0 0 ];
basisFunction{5} = [0 0 0 0 0 0 0 0 ;
0 0 1 1 1 1 0 0 ;
0 0 1 0 0 0 0 0;
0 0 1 1 1 1 0 0;
0 0 0 0 1 1 0 0 ;
0 0 0 0 1 1 0 0 ;
0 0 1 1 1 1 0 0 ;
0 0 0 0 0 0 0 0 ];
basisFunction{6} = [0 0 0 0 0 0 0 0 ;
0 0 0 1 1 1 0 0 ;
0 0 1 0 0 0 0 0;
0 0 1 0 0 0 0 0;
0 0 1 0 1 1 0 0 ;
0 0 1 0 0 1 0 0 ;
0 0 1 1 1 1 0 0 ;
0 0 0 0 0 0 0 0 ];
basisFunction{7} = [0 0 0 0 0 0 0 0 ;
0 0 1 1 1 1 0 0 ;
0 0 0 0 0 1 0 0;
0 0 0 0 1 1 0 0;
0 0 0 1 1 0 0 0 ;
0 0 0 1 0 0 0 0 ;
0 0 0 1 0 0 0 0 ;
0 0 0 0 0 0 0 0 ];
basisFunction{8} = [0 0 0 0 0 0 0 0 ;
0 0 1 1 1 1 0 0 ;
0 0 1 0 0 1 0 0;
0 0 1 1 1 1 0 0;
0 0 1 1 1 1 0 0 ;
0 0 1 0 0 1 0 0 ;
0 0 1 1 1 1 0 0 ;
0 0 0 0 0 0 0 0 ];
basisFunction{9} = [0 0 0 0 0 0 0 0 ;
0 0 1 1 1 1 0 0 ;
0 0 1 0 0 1 0 0;
0 0 1 1 1 1 0 0;
0 0 0 0 0 1 0 0 ;
0 0 0 0 0 1 0 0 ;
0 0 1 1 1 1 0 0 ;
0 0 0 0 0 0 0 0 ];
basisFunction{10} = [0 0 0 0 0 0 0 0 ;
0 0 1 1 1 1 0 0 ;
0 0 1 0 0 1 0 0;
0 0 1 0 0 1 0 0;
0 0 1 0 0 1 0 0 ;
0 0 1 0 0 1 0 0 ;
0 0 1 1 1 1 0 0 ;
0 0 0 0 0 0 0 0 ];
counter = 1;
for i=1:10
d = basisFunction{i};
d1 = [zeros(8,2),d(:,1:6)];
d2 = [d(:,3:end),zeros(8,2)];
d3 = [zeros(1,8); d(1:7,:)];
d4 = [d(1:7,:); zeros(1,8)];
d5 = [zeros(1,8); d1(1:7,:)];
d6 = [zeros(1,8); d2(1:7,:)];
d7 = [d1(1:7,:); zeros(1,8)];
d8 = [d2(1:7,:); zeros(1,8)];
d = d(:);d1 = d1(:); d2 = d2(:);d3 = d3(:);d4 = d4(:);d5 = d5(:);d6 = d6(:);d7 = d7(:);d8 = d8(:);
A(:,counter) = d/(d'*d);
A(:,counter+1) = d1/(d1'*d1);
A(:,counter+2) = d2/(d2'*d2);
A(:,counter+3) = d3/(d3'*d3);
A(:,counter+4) = d4/(d4'*d4);
A(:,counter+5) = d5/(d5'*d5);
A(:,counter+6) = d6/(d6'*d6);
A(:,counter+7) = d7/(d7'*d7);
A(:,counter+8) = d8/(d8'*d8);
counter = counter+9;
end
positiveFlag = 1;
[D,xOrig] = CreateDataFromDictionarySimple(A, numRequiredPoints,param.L,...
positiveFlag);
noise = randn(size(D));
if (SNR==0)
D = D;
else
actualNoise = calcNoiseFromSNR(SNR,D, noise);
D = D + actualNoise;
end
A = A./repmat(sqrt(diag(A'*A)'),64,1);
displayDictionaryElementsAsImage(A, 10, 9,8,8,0);
title('Original dictionary');
param.TrueDictionary = A;
param.preserveDCAtom = 0;
param.displayProgress = 1;
%=============================================
% Run the NN-KSVD function
%=============================================
[Dictionary,output] = KSVD_NN(D,param);
%=============================================
% display the results
%=============================================
Dictionary = Dictionary./repmat(sqrt(diag(Dictionary'*Dictionary)'),64,1);
figure(1)
displayDictionaryElementsAsImage(Dictionary,10, 9,8,8,0);
title(['Found dictionary']);
figure(2);
function [D,xOrig] = CreateDataFromDictionarySimple(dictionary, numElements, numCoef,positiveFlag)
maxRangeOfCoef = 1;
resolution = 0.0001;
xOrig = zeros(size(dictionary,2),numElements);
coefs = randn(numCoef,numElements)*maxRangeOfCoef;
if (positiveFlag)
idx = find(coefs<0);
coefs(idx) = coefs(idx)*-1;
end
xOrig(1:numCoef,:) = coefs;
for i=1:size(xOrig,2)
xOrig(:,i) = xOrig(randperm(size(xOrig,1)),i);
end
%dictionaryElementIndices = randsrc(numCoef*numElements,1,[1:size(dictionary,2)]) ;
%matrixOfIndices = repmat([1:numElements],numCoef,1);
%xOrig(sub2ind(size(xOrig),dictionaryElementIndices,matrixOfIndices(:))) = coefs;
D = dictionary*xOrig;
function actualNoise = calcNoiseFromSNR(TargerSNR, signal, randomNoise)
signal = signal(:);
randomNoiseRow = randomNoise(:);
signal_2 = sum(signal.^2);
ActualNoise_2 = signal_2/(10^(TargerSNR/10));
noise_2 = sum(randomNoiseRow.^2);
ratio = ActualNoise_2./noise_2;
actualNoise = randomNoiseRow.*repmat(sqrt(ratio),size(randomNoiseRow,1),1);
actualNoise = reshape(actualNoise,size(randomNoise));
|
github
|
chuangao/BicMix-master
|
MOD.m
|
.m
|
BicMix-master/KSVD/MOD.m
| 8,053 |
utf_8
|
f5300aadcb0fbf0ade04eca1adf42577
|
function [Dictionary,output] = MOD(Data,param)
% =========================================================================
% MOD algorithm
% =========================================================================
% Given for comparison reasons only. For detils please see the paper
% "Method of optimal directions for frame design", written by K. Engan,
% S.O. Aase, and J.H. Husfy, appeared in the IEEE International Conference
% on Acoustics, Speech, and Signal Processing, 1999.
% =========================================================================
% INPUT ARGUMENTS:
% Data an nXN matrix that contins N signals (Y), each of dimension n.
% param structure that includes all required
% parameters for the K-SVD execution.
% Required fields are:
% K, ... the number of dictionary elements to train
% numIteration,... number of iterations to perform.
% errorFlag... if =0, a fix number of coefficients is
% used for representation of each signal. If so, param.L must be
% specified as the number of representing atom. if =1, arbitrary number
% of atoms represent each signal, until a specific representation error
% is reached. If so, param.errorGoal must be specified as the allowed
% error.
% (optional, see errorFlag) L,... % maximum coefficients to use in OMP coefficient calculations.
% (optional, see errorFlag) errorGoal, ... % allowed representation error in representing each signal.
% InitializationMethod,... mehtod to initialize the dictionary, can
% be one of the following arguments:
% * 'DataElements' (initialization by the signals themselves), or:
% * 'GivenMatrix' (initialization by a given matrix param.initialDictionary).
% (optional, see InitializationMethod) initialDictionary,... % if the initialization method
% is 'GivenMatrix', this is the matrix that will be used.
% preserveDCAtom, ... =1 for a DC atom (in which all entries are equal) to be generated, and
% not changed throughout the training.
% (optional) TrueDictionary, ... % if specified, in each
% iteration the difference between this dictionary and the trained one
% is measured and displayed.
% displayProgress, ... if =1 progress information is displyed. If param.errorFlag==0,
% the average repersentation error (RMSE) is displayed, while if
% param.errorFlag==1, the average number of required coefficients for
% representation of each signal is displayed.
% =========================================================================
% OUTPUT ARGUMENTS:
% Dictionary The extracted dictionary of size nX(param.K).
% output Struct that contains information about the current run. It may include the following fields:
% CoefMatrix The final coefficients matrix (it should hold that Data equals approximately Dictionary*output.CoefMatrix.
% ratio If the true dictionary was defined (in
% synthetic experiments), this parameter holds a vector of length
% param.numIteration that includes the detection ratios in each
% iteration).
% totalerr The total representation error after each
% iteration (defined only if
% param.displayProgress=1 and
% param.errorFlag = 0)
% numCoef A vector of length param.numIteration that
% include the average number of coefficients required for representation
% of each signal (in each iteration) (defined only if
% param.displayProgress=1 and
% param.errorFlag = 1)
% =========================================================================
if (size(Data,2) < param.K)
disp('Size of data is smaller than the dictionary size. Trivial solution...');
Dictionary = Data(:,1:size(Data,2));
return;
elseif (strcmp(param.InitializationMethod,'DataElements'))
Dictionary(:,1:param.K) = Data(:,1:param.K);
elseif (strcmp(param.InitializationMethod,'GivenMatrix'))
Dictionary = param.initialDictionary;
end
%normalize the dictionary.
Dictionary = Dictionary*diag(1./sqrt(sum(Dictionary.*Dictionary)));
Dictionary = Dictionary.*repmat(sign(Dictionary(1,:)),size(Dictionary,1),1); % multiply in the sign of the first element.
K = size(Dictionary,2);
totalErr = zeros(1,param.numIteration);
if (size(param.TrueDictionary)==size(Dictionary))
displayErrorWithTrueDictionary = 1;
ErrorBetweenDictionaries = zeros(param.numIteration+1,1);
ratio = zeros(param.numIteration+1,1);
else
displayErrorWithTrueDictionary = 0;
end
numCoef = param.L;
for iterNum = 1:param.numIteration
% find the coefficients
if (param.errorFlag==0)
%CoefMatrix = mexOMPIterative2(Data, [FixedDictionaryElement,Dictionary],param.L);
CoefMatrix = OMP(Dictionary,Data, param.L);
else
%CoefMatrix = mexOMPerrIterative(Data, [FixedDictionaryElement,Dictionary],param.errorGoal);
CoefMatrix = OMPerr(Dictionary,Data, param.errorGoal);
param.L = 1;
end
% improve the dictionary
Dictionary = Data*CoefMatrix'*inv(CoefMatrix*CoefMatrix' + 1e-7*speye(size(CoefMatrix,1)));
sumDictElems = sum(abs(Dictionary));
zerosIdx = find(sumDictElems<eps);
Dictionary(:,zerosIdx) = randn(size(Dictionary,1),length(zerosIdx));
Dictionary = Dictionary*diag(1./sqrt(sum(Dictionary.*Dictionary)));
if (iterNum>1 & param.displayProgress)
if (param.errorFlag==0)
output.totalerr(iterNum-1) = sqrt(sum(sum((Data-Dictionary*CoefMatrix).^2))/prod(size(Data)));
disp(['Iteration ',num2str(iterNum),' Total error is: ',num2str(output.totalerr(iterNum-1))]);
else
output.numCoef(iterNum-1) = length(find(CoefMatrix))/size(Data,2);
disp(['Iteration ',num2str(iterNum),' Average number of coefficients: ',num2str(output.numCoef(iterNum-1))]);
end
end
if (displayErrorWithTrueDictionary )
[ratio(iterNum+1),ErrorBetweenDictionaries(iterNum+1)] = I_findDistanseBetweenDictionaries(param.TrueDictionary,Dictionary);
disp(strcat(['Iteration ', num2str(iterNum),' ratio of restored elements: ',num2str(ratio(iterNum+1))]));
output.ratio = ratio;
end
end
output.CoefMatrix = CoefMatrix;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% findDistanseBetweenDictionaries
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [ratio,totalDistances] = I_findDistanseBetweenDictionaries(original,new)
% first, all the column in oiginal starts with positive values.
catchCounter = 0;
totalDistances = 0;
for i = 1:size(new,2)
new(:,i) = sign(new(1,i))*new(:,i);
end
for i = 1:size(original,2)
d = sign(original(1,i))*original(:,i);
distances =sum ( (new-repmat(d,1,size(new,2))).^2);
[minValue,index] = min(distances);
errorOfElement = 1-abs(new(:,index)'*d);
totalDistances = totalDistances+errorOfElement;
catchCounter = catchCounter+(errorOfElement<0.01);
end
ratio = 100*catchCounter/size(original,2);
|
github
|
eardi/sm-fpca-master
|
test_FELICITY.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/test_FELICITY.m
| 3,998 |
utf_8
|
306a68c40b8cb43a10fdb91f4b94127a
|
function status = test_FELICITY()
%test_FELICITY
%
% Run the test suite for FELICITY.
% Copyright (c) 06-25-2020, Shawn W. Walker
VER_NUMBER = '1.3.1';
Test_Files( 1).FH = @compile_static_codes;
Test_Files( 2).FH = @test_utilities;
Test_Files( 3).FH = @test_static_codes;
Test_Files( 4).FH = @test_mesh_classes;
Test_Files( 5).FH = @test_elem_defn;
Test_Files( 6).FH = @test_fem_classes;
Test_Files( 7).FH = @test_managesim_classes;
Test_Files( 8).FH = @test_dof_numbering;
Test_Files( 9).FH = @test_matrix_assembly;
Test_Files(10).FH = @test_fel_pt_search;
Test_Files(11).FH = @test_fel_interpolation;
Test_Files(12).FH = @test_felicity_demos;
output_FELICITY();
FELICITY_user_help();
status = 1;
VALID = and(check_path_length(),check_dir_path_for_spaces());
if VALID
for ind = 1:length(Test_Files)
status = Test_Files(ind).FH();
if (status~=0)
disp('Test failed!');
disp(['See ----> ', func2str(Test_Files(ind).FH)]);
break;
end
end
else
status = -1;
end
if (status==0)
disp('<<<< All FELICITY tests passed >>>>');
disp(' ');
disp('*** Your FELICITY installation is fully functional ***');
output_FELICITY();
disp(['Version Number: ', VER_NUMBER]);
else
disp('<<<< ERROR >>>>');
disp(' ');
disp('*** Your FELICITY installation is NOT working... ***');
disp(' ');
end
end
function VALID = check_path_length()
% make sure root path length is not longer than 60 characters
PATH = [fileparts(mfilename('fullpath')), '\'];
LEN = length(PATH);
if LEN > 60
choice = questdlg({'It seems you installed FELICITY here:';
['''', PATH, '''.'];
['The length of this path is too long ', '(', num2str(LEN), ' chars long)', '.'];
'It is recommended that you install FELICITY closer to your root.';
'(Ideally, the path char length should be less than 60.)'
'Otherwise, the unit tests may fail!';
'';
'Do you wish to continue with unit testing?'}, ...
'FELICITY Root Directory', 'Abort','Continue','Continue');
if strcmp(choice,'Abort')
VALID = false;
else
VALID = true;
end
else
VALID = true;
end
end
function VALID = check_dir_path_for_spaces()
% make sure root path does not contain space characters
PATH = [fileparts(mfilename('fullpath')), '\'];
NO_space = isempty(regexp(PATH, '\s', 'once'));
if (~NO_space) % if there is a space...
choice = questdlg({'It seems you installed FELICITY here:';
['''', PATH, '''.'];
'Some of the folder names in the root contain a "space" character.';
'For example, you may have installed under the directory:';
' ''C:\Program Files\...''';
'This is *not* recommended!';
'You should install FELICITY under a directory *without* spaces.';
'Otherwise, the unit tests may fail!';
'';
'Do you wish to continue with unit testing?'}, ...
'FELICITY Root Directory', 'Abort','Continue','Continue');
if strcmp(choice,'Abort')
VALID = false;
else
VALID = true;
end
else
VALID = true;
end
end
function output_FELICITY()
disp(' ');
disp(' ______ ______ _ _____ _____ _____ _________ __');
disp('| ____| ____| | |_ _/ ____|_ _|__ __\ \ / /');
disp('| |__ | |__ | | | || | | | | | \ \_/ / ');
disp('| __| | __| | | | || | | | | | \ / ');
disp('| | | |____| |____ _| || |____ _| |_ | | | | ');
disp('|_| |______|______|_____\_____|_____| |_| |_| ');
disp(' ');
end
|
github
|
eardi/sm-fpca-master
|
Generate_HellanHerrmannJohnson_Element_File.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Elem_Defn/Generators/Generate_HellanHerrmannJohnson_Element_File.m
| 15,770 |
utf_8
|
5b5b568e3b4aafb16244458c239e1511
|
function status = Generate_HellanHerrmannJohnson_Element_File(Element_Domain,Degree_k,Output_Dir)
%Generate_HellanHerrmannJohnson_Element_File
%
% This generates a finite element reference m-file that defines a
% particular Hellan-Herrmann-Johnson element of given fixed degree on a
% given reference domain.
%
% The inputs are:
% Element_Domain = 'interval', 'triangle', 'tetrahedron', etc.
% Degree_k = polynomial degree of finite element.
% Output_Dir = string specifying where to write the file.
% Copyright (c) 03-22-2018, Shawn W. Walker
% get basic info text
[Element_Domain, Domain_STR, Domain_Fig_ASCII, Dim] = setup_generic_element_file_text(Element_Domain);
ENDL = '\n';
TAB = ' ';
%TAB2 = [TAB, TAB];
%TAB3 = [TAB2, TAB];
%TAB4 = [TAB3, TAB];
% get the (reference) finite element space
if strcmpi(Element_Domain,'interval')
error('Invalid domain!');
elseif strcmpi(Element_Domain,'triangle')
[Nodal_Basis, Nodal_Var] = Get_HellanHerrmannJohnson_On_Simplex(Dim,Degree_k);
elseif strcmpi(Element_Domain,'tetrahedron')
[Nodal_Basis, Nodal_Var] = Get_HellanHerrmannJohnson_On_Simplex(Dim,Degree_k);
else
error('Not implemented!');
end
% setup filename
Degree_str = num2str(Degree_k);
Dim_str = num2str(Dim);
FuncName = ['hellan_herrmann_johnson_deg', Degree_str, '_dim', Dim_str];
Output_FileName = fullfile(Output_Dir, [FuncName, '.m']);
% open file for writing
fid = fopen(Output_FileName, 'w');
% define write line function
write_line = @(STR) fprintf(fid, [STR, ENDL]);
write_string = @(STR) fprintf(fid, STR);
% write header
write_line(['', 'function Elem = ', FuncName, '(Type_STR)']);
write_line(['%%', FuncName]);
write_line(['%%']);
write_line(['%%', TAB, 'This defines a reference finite element to be used by FELICITY.']);
write_line(['%%', TAB, 'INPUT: string = ''CG''/''DG'' (continuous/DIScontinuous galerkin).']);
write_line(['%%']);
write_line(['%%', TAB, 'Hellan-Herrmann-Johnson H(div div) Finite Element of degree = ', Degree_str, ', in dimension = ', Dim_str, '.']);
write_line(['%%']);
write_line(['%%', TAB, 'Reference Domain: ', Domain_STR, '.']);
write_line(['%%']);
write_string([Domain_Fig_ASCII]);
write_line(['%%']);
write_line(['%%', TAB, 'The basis functions are matrix-valued (size = topological dimension X topological dimension).']);
write_line(['%%']);
write_line(['%%', TAB, 'The basis functions associated with Degrees-of-Freedom (DoFs) on a facet']);
write_line(['%%', TAB, 'are "normal-normal" components of the matrix, so facet orientation is *not* needed.']);
write_line(['']);
current_date = date;
write_line(['%%', ' Copyright (c) ', current_date, ', Shawn W. Walker']);
write_line(['']);
write_line(['%% name it!']);
write_line(['Elem.Name = mfilename;']);
write_line(['']);
write_line(['%% determine continuous or discontinuous galerkin space']);
write_line(['if (nargin==0)']);
write_line([TAB, 'Type_STR = ''CG''; %% default']);
write_line(['end']);
write_line(['if strcmpi(Type_STR,''cg'')']);
write_line([TAB, 'Elem.Type = ''CG'';']);
write_line(['elseif strcmpi(Type_STR,''dg'')']);
write_line([TAB, 'Elem.Type = ''DG'';']);
write_line(['else']);
write_line([TAB, 'error(''Invalid input type! Must be ''''CG'''' or ''''DG''''.'');']);
write_line(['end']);
write_line(['']);
write_line(['%% topological dimension and domain']);
write_line(['Elem.Dim = ', Dim_str, ';']);
write_line(['Elem.Domain = ''', Element_Domain, ''';']);
write_line(['']);
write_line(['%% nodal basis function definitions (in the order of their local Degree-of-Freedom index)']);
Num_Basis = length(Nodal_Basis);
write_line(['Elem.Basis(', num2str(Num_Basis), ').Func = []; %% init']);
% loop through nodal basis
for ii = 1:length(Nodal_Basis)
BF = Nodal_Basis(ii).Func;
Basis_Func_Str = write_element_file_basis_func_string(BF);
write_line(['Elem.Basis(', num2str(ii), ').Func = {', Basis_Func_Str, '};']);
end
write_line(['%% local mapping transformation to use']);
Transformation_Type_str = 'Hdivdiv_Trans';
write_line(['Elem.Transformation = ''', Transformation_Type_str, ''';']);
write_line(['Elem.Degree = ', Degree_str, ';']);
write_line(['']);
write_line(['%% nodal variable data (in the order of their local Degree-of-Freedom index)']);
write_line(['%% (the nodal point is given in barycentric coordinates)']);
Num_Nodal_Var = length(Nodal_Var);
write_line(['Elem.Nodal_Var(', num2str(Num_Nodal_Var), ').Data = []; %% init']);
% loop through nodal variables
for ii = 1:length(Nodal_Var)
NV = Nodal_Var(ii).Data;
Nodal_BC_str = write_element_file_barycentric_string(NV{1});
% write Hellan-Herrmann-Johnson element nodal variable data string
if strcmpi(NV{3},'int_facet')
Dual_Basis_str = ['[', char(NV{2}), ']'];
Nodal_Var_Data_str = ['{', Nodal_BC_str, ', ''', Dual_Basis_str, ''', ''', NV{3}, ''', ', num2str(NV{4}), '}'];
elseif strcmpi(NV{3},'int_cell')
% generate string for dual basis function
BF = NV{2};
if (Dim==2)
DB_11 = char(BF(1,1));
DB_12 = char(BF(1,2));
DB_21 = char(BF(2,1));
DB_22 = char(BF(2,2));
Dual_Basis_str = ['[', DB_11, ', ', DB_12, '; ', DB_21, ', ', DB_22 ']'];
elseif (Dim==3)
DB_1 = char(BF(1));
DB_2 = char(BF(2));
DB_3 = char(BF(3));
error('Not implemented!');
Dual_Basis_str = ['[', DB_1, '; ', DB_2, '; ', DB_3, ']'];
elseif (Dim==1)
error('Invalid!');
else
error('Not implemented!');
end
Nodal_Var_Data_str = ['{', Nodal_BC_str, ', ''', Dual_Basis_str, ''', ''', NV{3}, ''', ',...
num2str(NV{4}), ', ''', NV{5}, ''', ', num2str(NV{6}), '}'];
else
error('Invalid!');
end
write_line(['Elem.Nodal_Var(', num2str(ii), ').Data = ', Nodal_Var_Data_str, ';']);
end
write_line(['']);
write_line(['%%%%%%%%%% topological arrangement of nodal points %%%%%%%%%%']);
write_line(['%% note: multiple sets of nodal variables can be associated with each topological entity.']);
write_line(['%% This is done by defining multiple matrix arrays within each matlab cell.']);
write_line(['%% See the FELICITY manual for more info.']);
write_line(['']);
Nodal_Top = get_nodal_top_arrangement(Element_Domain,Nodal_Var);
DoF_TAB = ' ';
write_line(['%% nodes attached to vertices']);
if ~isempty(Nodal_Top.V{1})
write_line(['Elem.Nodal_Top.V = {...']);
Nodal_Sets_str = write_element_file_nodal_top_string(Nodal_Top.V,DoF_TAB);
write_line(Nodal_Sets_str);
write_line([DoF_TAB, '};']);
write_line(['%%']);
else
write_line(['Elem.Nodal_Top.V = {[]};']);
end
write_line(['']);
write_line(['%% nodes attached to edges']);
if ~isempty(Nodal_Top.E{1})
write_line(['Elem.Nodal_Top.E = {...']);
Nodal_Sets_str = write_element_file_nodal_top_string(Nodal_Top.E,DoF_TAB);
write_line(Nodal_Sets_str);
write_line([DoF_TAB, '};']);
write_line(['%%']);
else
write_line(['Elem.Nodal_Top.E = {[]};']);
end
write_line(['']);
write_line(['%% nodes attached to triangles (faces)']);
if ~isempty(Nodal_Top.F{1})
write_line(['Elem.Nodal_Top.F = {...']);
Nodal_Sets_str = write_element_file_nodal_top_string(Nodal_Top.F,DoF_TAB);
write_line(Nodal_Sets_str);
write_line([DoF_TAB, '};']);
write_line(['%%']);
else
write_line(['Elem.Nodal_Top.F = {[]};']);
end
write_line(['']);
write_line(['%% nodes attached to tetrahedra (cells)']);
if ~isempty(Nodal_Top.T{1})
write_line(['Elem.Nodal_Top.T = {...']);
Nodal_Sets_str = write_element_file_nodal_top_string(Nodal_Top.T,DoF_TAB);
write_line(Nodal_Sets_str);
write_line([DoF_TAB, '};']);
write_line(['%%']);
else
write_line(['Elem.Nodal_Top.T = {[]};']);
end
write_line(['']);
write_string(['end']);
% DONE!
status = fclose(fid);
end
function Nodal_Top = get_nodal_top_arrangement(Element_Domain,Nodal_Var)
%
% This arranges the nodal variables (i.e. the nodal points) on their
% corresponding topological entities.
if strcmpi(Element_Domain,'interval')
% this is invalid!
Nodal_Top.V = {[]};
Nodal_Top.E = {[]};
Nodal_Top.F = {[]};
Nodal_Top.T = {[]};
elseif strcmpi(Element_Domain,'triangle')
% init
Edge1 = [];
Edge2 = [];
Edge3 = [];
Cell_1 = [];
Cell_2 = [];
Cell_3 = [];
for ind = 1:length(Nodal_Var)
NV = Nodal_Var(ind).Data;
Pt = NV{1};
BC_Pt = double(convert_to_barycentric(Pt))';
Type = NV{3};
Entity_Index = NV{4};
if strcmpi(Type,'int_facet')
if (Entity_Index==1)
Edge1 = [Edge1; ind, BC_Pt];
elseif (Entity_Index==2)
Edge2 = [Edge2; ind, BC_Pt];
elseif (Entity_Index==3)
Edge3 = [Edge3; ind, BC_Pt];
else
error('Invalid!');
end
elseif strcmpi(Type,'int_cell')
dof_set = NV{6};
if (dof_set==1)
Cell_1 = [Cell_1; ind, BC_Pt];
elseif (dof_set==2)
Cell_2 = [Cell_2; ind, BC_Pt];
elseif (dof_set==3)
Cell_3 = [Cell_3; ind, BC_Pt];
else
error('Invalid!');
end
else
error('Invalid!');
end
end
Num_E1 = size(Edge1,1);
Num_E2 = size(Edge2,1);
Num_E3 = size(Edge3,1);
Num_C1 = size(Cell_1,1);
Num_C2 = size(Cell_2,1);
Num_C3 = size(Cell_3,1);
Num_DoF = Num_E1 + Num_E2 + Num_E3 + Num_C1 + Num_C2 + Num_C3;
if (Num_DoF~=length(Nodal_Var))
error('Number of DoFs is incorrect!');
end
CHK_EDGE_DOF = max(abs([Num_E1, Num_E2, Num_E3] - Num_E1));
if (CHK_EDGE_DOF~=0)
error('Number of Edge DoFs on each edge is not the same!');
end
CHK_CELL_DOF = max(abs([Num_C1, Num_C2, Num_C3] - Num_C1));
if (CHK_CELL_DOF~=0)
error('Number of Cell DoFs in each set is not the same!');
end
% there are no vertex DoFs
Nodal_Top.V = {[]};
% setup the facet (edge) DoFs
Edge1 = sortrows(Edge1,1); % sort based on DoF index
Edge2 = sortrows(Edge2,1);
Edge3 = sortrows(Edge3,1);
DoFs_on_Edge = [Edge1(:,1)'; Edge2(:,1)'; Edge3(:,1)'];
Nodal_Top.E = {DoFs_on_Edge};
% setup the cell (face) DoFs
if ~isempty(Cell_1)
Cell_1 = sortrows(Cell_1,1); % sort based on DoF index
Cell_2 = sortrows(Cell_2,1);
Cell_3 = sortrows(Cell_3,1);
DoFs_on_Face_1 = [Cell_1(:,1)'];
DoFs_on_Face_2 = [Cell_2(:,1)'];
DoFs_on_Face_3 = [Cell_3(:,1)'];
% there are 3 sets of DoFs (one for each symmetric matrix basis component in 2-D)
Nodal_Top.F = {DoFs_on_Face_1, DoFs_on_Face_2, DoFs_on_Face_3};
else
Nodal_Top.F = {[]};
end
% there are no other DoFs
Nodal_Top.T = {[]};
elseif strcmpi(Element_Domain,'tetrahedron')
% init
Face1 = [];
Face2 = [];
Face3 = [];
Face4 = [];
Cell_1 = [];
Cell_2 = [];
Cell_3 = [];
Cell_4 = [];
Cell_5 = [];
Cell_6 = [];
error('not implemented correctly!');
for ind = 1:length(Nodal_Var)
NV = Nodal_Var(ind).Data;
Pt = NV{1};
BC_Pt = double(convert_to_barycentric(Pt))';
Type = NV{3};
Entity_Index = NV{4};
if strcmpi(Type,'int_facet')
if (Entity_Index==1)
Face1 = [Face1; ind, BC_Pt];
elseif (Entity_Index==2)
Face2 = [Face2; ind, BC_Pt];
elseif (Entity_Index==3)
Face3 = [Face3; ind, BC_Pt];
elseif (Entity_Index==4)
Face4 = [Face4; ind, BC_Pt];
else
error('Invalid!');
end
elseif strcmpi(Type,'int_cell')
dof_set = NV{6};
if (dof_set==1)
Cell_1 = [Cell_1; ind, BC_Pt];
elseif (dof_set==2)
Cell_2 = [Cell_2; ind, BC_Pt];
elseif (dof_set==3)
Cell_3 = [Cell_3; ind, BC_Pt];
elseif (dof_set==4)
Cell_4 = [Cell_4; ind, BC_Pt];
elseif (dof_set==5)
Cell_5 = [Cell_5; ind, BC_Pt];
elseif (dof_set==6)
Cell_6 = [Cell_6; ind, BC_Pt];
else
error('Invalid!');
end
else
error('Invalid!');
end
end
Num_F1 = size(Face1,1);
Num_F2 = size(Face2,1);
Num_F3 = size(Face3,1);
Num_F4 = size(Face4,1);
Num_C1 = size(Cell_1,1);
Num_C2 = size(Cell_2,1);
Num_C3 = size(Cell_3,1);
Num_C4 = size(Cell_4,1);
Num_C5 = size(Cell_5,1);
Num_C6 = size(Cell_6,1);
Num_DoF = Num_F1 + Num_F2 + Num_F3 + Num_F4 + ...
Num_C1 + Num_C2 + Num_C3 + Num_C4 + Num_C5 + Num_C6;
if (Num_DoF~=length(Nodal_Var))
error('Number of DoFs is incorrect!');
end
CHK_FACE_DOF = max(abs([Num_F1, Num_F2, Num_F3, Num_F4] - Num_F1));
if (CHK_FACE_DOF~=0)
error('Number of Face DoFs on each face is not the same!');
end
CHK_CELL_DOF = max(abs([Num_C1, Num_C2, Num_C3, Num_C4, Num_C5, Num_C6] - Num_C1));
if (CHK_CELL_DOF~=0)
error('Number of Cell DoFs in each set is not the same!');
end
% there are no vertex DoFs
Nodal_Top.V = {[]};
% there are no edge DoFs
Nodal_Top.E = {[]};
% setup the facet (face) DoFs
Face1 = sortrows(Face1,1); % sort based on DoF index
Face2 = sortrows(Face2,1);
Face3 = sortrows(Face3,1);
Face4 = sortrows(Face4,1);
DoFs_on_Face = [Face1(:,1)'; Face2(:,1)'; Face3(:,1)'; Face4(:,1)'];
Nodal_Top.F = {DoFs_on_Face};
% setup the cell (tet) DoFs
if ~isempty(Cell_1)
Cell_1 = sortrows(Cell_1,1); % sort based on DoF index
Cell_2 = sortrows(Cell_2,1);
Cell_3 = sortrows(Cell_3,1);
Cell_4 = sortrows(Cell_4,1);
Cell_5 = sortrows(Cell_5,1);
Cell_6 = sortrows(Cell_6,1);
DoFs_on_Cell_1 = [Cell_1(:,1)'];
DoFs_on_Cell_2 = [Cell_2(:,1)'];
DoFs_on_Cell_3 = [Cell_3(:,1)'];
DoFs_on_Cell_4 = [Cell_4(:,1)'];
DoFs_on_Cell_5 = [Cell_5(:,1)'];
DoFs_on_Cell_6 = [Cell_6(:,1)'];
% there are 6 sets of DoFs (one for each symmetric matrix basis component in 3-D)
Nodal_Top.T = {DoFs_on_Cell_1, DoFs_on_Cell_2, DoFs_on_Cell_3,...
DoFs_on_Cell_4, DoFs_on_Cell_5, DoFs_on_Cell_6};
else
Nodal_Top.T = {[]};
end
else
error('Not implemented!');
end
Vtx_DoFs = [];
for ii = 1:length(Nodal_Top.V)
Vtx_DoFs = [Vtx_DoFs; Nodal_Top.V{ii}(:)];
end
Edge_DoFs = [];
for ii = 1:length(Nodal_Top.E)
Edge_DoFs = [Edge_DoFs; Nodal_Top.E{ii}(:)];
end
Face_DoFs = [];
for ii = 1:length(Nodal_Top.F)
Face_DoFs = [Face_DoFs; Nodal_Top.F{ii}(:)];
end
Tet_DoFs = [];
for ii = 1:length(Nodal_Top.T)
Tet_DoFs = [Tet_DoFs; Nodal_Top.T{ii}(:)];
end
All_DoFs = [Vtx_DoFs; Edge_DoFs; Face_DoFs; Tet_DoFs];
% final check
Unique_DoFs = unique(All_DoFs);
if (length(All_DoFs)~=length(Unique_DoFs))
error('Not all DoF indices are distinct!');
end
end
|
github
|
eardi/sm-fpca-master
|
Get_Lagrange_On_Simplex.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Elem_Defn/Generators/Get_Lagrange_On_Simplex.m
| 24,400 |
utf_8
|
7650a20938204235c125a8f0ea449dcd
|
function [Nodal_Basis, Nodal_Var] = Get_Lagrange_On_Simplex(dim,deg_k)
%Get_Lagrange_On_Simplex
%
% This computes the Lagrange basis functions on a simplex.
% Copyright (c) 09-24-2016, Shawn W. Walker
disp(['Solve for Lagrange degree ', num2str(deg_k), ' basis functions (on ', num2str(dim), '-D reference simplex):']);
if (deg_k < 0)
% invalid degree, so return *nothing*
Nodal_Basis = [];
Nodal_Var = [];
return;
end
% get parameterizations of the reference simplex
if (dim==1)
% get params of the reference interval
Cell = interval_parameterizations();
elseif (dim==2)
% get params of the reference triangle
Cell = triangle_parameterizations();
elseif (dim==3)
% get params of the reference tetrahedron
Cell = tetrahedron_parameterizations();
else
error('Not implemented!');
end
indep_vars = Cell.Param_Inv; % col. vector list of independent variables
% define a set of basis functions (indep. variables are x,y,z, depending on dimension)
Basis = basis_polys_deg_k(indep_vars,deg_k);
% error check
Num_Basis = nchoosek(dim + deg_k,deg_k);
if (Num_Basis~=length(Basis))
error('Number of basis functions is invalid!');
end
% define nodal variable data
if (dim==1)
Nodal_Var = lagrange_nodal_points_1D(deg_k);
elseif (dim==2)
Nodal_Var = lagrange_nodal_points_2D(deg_k);
elseif (dim==3)
Nodal_Var = lagrange_nodal_points_3D(deg_k);
else
error('Not implemented!');
end
% generate matrix entries
N = length(Nodal_Var);
if (N~=Num_Basis) % error check
error('Number of nodal variables is not correct!');
end
% init Vandermonde matrix
A = sym(zeros(N,N));
% fill in the "Vandermonde" matrix
disp('Fill Vandermonde matrix A:');
for ii=1:N
% get the current nodal variable (DoF)
Nodal_Var_Data = Nodal_Var(ii).Data;
Eval_Nodal_Variable = Lagrange_Nodal_Variable(Cell,Nodal_Var_Data,indep_vars);
% loop through all of the (primal) basis functions
for jj=1:N
phi = Basis(jj).func; % get basis function
% insert into matrix
A(ii,jj) = Eval_Nodal_Variable(phi); % eval nodal variable
end
disp(['Compute A(', num2str(ii), ', 1:', num2str(N), ').']);
end
disp('Finished forming Vandermonde matrix...');
% lambda = abs(eig(double(A)));
% COND = max(lambda) / min(lambda);
% COND
% solve for coefficients
EYE_SYM = sym(eye(N));
disp('Solve for coefficients:');
COEF = A \ EYE_SYM;
% compute the nodal basis functions
Nodal_Basis(N).Func = [];
for ind=1:N
TEMP = 0; % reset!
for jj=1:N
TEMP = TEMP + COEF(jj,ind) * Basis(jj).func;
end
Nodal_Basis(ind).Func = simplify(TEMP);
end
% display
for ind=1:N
disp(['Nodal Basis Function #', num2str(ind), ':']);
pretty(Nodal_Basis(ind).Func)
end
end
function Nodal_Var = lagrange_nodal_points_1D(deg_k)
% lay out the points on the reference interval, starting with the end
% points (for degree k >= 1). For degree k = 0, just the midpoint.
NV = deg_k+1;
Nodal_Var(NV).Data = [];
% define nodal variable data (in order of the DoF index)
% these specify what the Degrees-of-Freedom (DoFs) are
% Note: these involve point evaluations (reference coordinates are given)
if (deg_k==0)
Nodal_Var(1).Data = {sym([0.5]), 'eval_cell', 1}; % point eval on cell
else
Nodal_Var(1).Data = {sym([0]), 'eval_vertex', 1}; % point eval on vertex #1
Nodal_Var(2).Data = {sym([1]), 'eval_vertex', 2}; % point eval on vertex #2
% now allocate the rest on the cell
if NV >= 3
pts = linspace(0,1,NV)';
pts = pts(2:end-1,1); % remove end points
for jj = 1:length(pts)
Nodal_Var(jj+2).Data = {sym(pts(jj)), 'eval_cell', 1}; % point eval on edge #1
end
end
end
end
function Nodal_Var = lagrange_nodal_points_2D(deg_k)
% lay out the points on the reference triangle, starting with the vertices
% (for degree k >= 1). For degree k = 0, just the barycenter.
NV = nchoosek(2 + deg_k,deg_k);
Nodal_Var(NV).Data = [];
% define nodal variable data (in order of the DoF index)
% these specify what the Degrees-of-Freedom (DoFs) are
% Note: these involve point evaluations (reference coordinates are given)
if (deg_k==0)
Nodal_Var(1).Data = {sym([(1/3); (1/3)]), 'eval_cell', 1}; % point eval on cell
else
Nodal_Var(1).Data = {sym([0; 0]), 'eval_vertex', 1}; % point eval on vertex #1
Nodal_Var(2).Data = {sym([1; 0]), 'eval_vertex', 2}; % point eval on vertex #2
Nodal_Var(3).Data = {sym([0; 1]), 'eval_vertex', 3}; % point eval on vertex #3
% now allocate the rest on the facets and the cell
if NV >= 4
if (deg_k==2)
Nodal_Var(4).Data = {sym([(1/2); (1/2)]), 'eval_facet', 1}; % point eval on facet (edge) #1
Nodal_Var(5).Data = {sym([0; (1/2)]), 'eval_facet', 2}; % point eval on facet (edge) #2
Nodal_Var(6).Data = {sym([(1/2); 0]), 'eval_facet', 3}; % point eval on facet (edge) #3
elseif (deg_k==3)
Nodal_Var( 4).Data = {sym([(2/3); (1/3)]), 'eval_facet', 1}; % point eval on facet (edge) #1
Nodal_Var( 5).Data = {sym([(1/3); (2/3)]), 'eval_facet', 1}; % point eval on facet (edge) #1
Nodal_Var( 6).Data = {sym([0; (2/3)]), 'eval_facet', 2}; % point eval on facet (edge) #2
Nodal_Var( 7).Data = {sym([0; (1/3)]), 'eval_facet', 2}; % point eval on facet (edge) #2
Nodal_Var( 8).Data = {sym([(1/3); 0]), 'eval_facet', 3}; % point eval on facet (edge) #3
Nodal_Var( 9).Data = {sym([(2/3); 0]), 'eval_facet', 3}; % point eval on facet (edge) #3
Nodal_Var(10).Data = {sym([(1/3); (1/3)]), 'eval_cell', 1}; % point eval on cell
elseif (deg_k==4)
Nodal_Var( 4).Data = {sym([(3/4); (1/4)]), 'eval_facet', 1}; % point eval on facet (edge) #1
Nodal_Var( 5).Data = {sym([(1/2); (1/2)]), 'eval_facet', 1}; % point eval on facet (edge) #1
Nodal_Var( 6).Data = {sym([(1/4); (3/4)]), 'eval_facet', 1}; % point eval on facet (edge) #1
Nodal_Var( 7).Data = {sym([0; (3/4)]), 'eval_facet', 2}; % point eval on facet (edge) #2
Nodal_Var( 8).Data = {sym([0; (1/2)]), 'eval_facet', 2}; % point eval on facet (edge) #2
Nodal_Var( 9).Data = {sym([0; (1/4)]), 'eval_facet', 2}; % point eval on facet (edge) #2
Nodal_Var(10).Data = {sym([(1/4); 0]), 'eval_facet', 3}; % point eval on facet (edge) #3
Nodal_Var(11).Data = {sym([(1/2); 0]), 'eval_facet', 3}; % point eval on facet (edge) #3
Nodal_Var(12).Data = {sym([(3/4); 0]), 'eval_facet', 3}; % point eval on facet (edge) #3
Nodal_Var(13).Data = {sym([(1/4); (1/4)]), 'eval_cell', 1}; % point eval on cell
Nodal_Var(14).Data = {sym([(1/2); (1/4)]), 'eval_cell', 1}; % point eval on cell
Nodal_Var(15).Data = {sym([(1/4); (1/2)]), 'eval_cell', 1}; % point eval on cell
elseif (deg_k==5)
Nodal_Var( 4).Data = {sym([(4/5); (1/5)]), 'eval_facet', 1}; % point eval on facet (edge) #1
Nodal_Var( 5).Data = {sym([(3/5); (2/5)]), 'eval_facet', 1}; % point eval on facet (edge) #1
Nodal_Var( 6).Data = {sym([(2/5); (3/5)]), 'eval_facet', 1}; % point eval on facet (edge) #1
Nodal_Var( 7).Data = {sym([(1/5); (4/5)]), 'eval_facet', 1}; % point eval on facet (edge) #1
Nodal_Var( 8).Data = {sym([0; (4/5)]), 'eval_facet', 2}; % point eval on facet (edge) #2
Nodal_Var( 9).Data = {sym([0; (3/5)]), 'eval_facet', 2}; % point eval on facet (edge) #2
Nodal_Var(10).Data = {sym([0; (2/5)]), 'eval_facet', 2}; % point eval on facet (edge) #2
Nodal_Var(11).Data = {sym([0; (1/5)]), 'eval_facet', 2}; % point eval on facet (edge) #2
Nodal_Var(12).Data = {sym([(1/5); 0]), 'eval_facet', 3}; % point eval on facet (edge) #3
Nodal_Var(13).Data = {sym([(2/5); 0]), 'eval_facet', 3}; % point eval on facet (edge) #3
Nodal_Var(14).Data = {sym([(3/5); 0]), 'eval_facet', 3}; % point eval on facet (edge) #3
Nodal_Var(15).Data = {sym([(4/5); 0]), 'eval_facet', 3}; % point eval on facet (edge) #3
Nodal_Var(16).Data = {sym([(2/5); (2/5)]), 'eval_cell', 1}; % point eval on cell
Nodal_Var(17).Data = {sym([(1/5); (1/5)]), 'eval_cell', 1}; % point eval on cell
Nodal_Var(18).Data = {sym([(1/5); (2/5)]), 'eval_cell', 1}; % point eval on cell
Nodal_Var(19).Data = {sym([(3/5); (1/5)]), 'eval_cell', 1}; % point eval on cell
Nodal_Var(20).Data = {sym([(2/5); (1/5)]), 'eval_cell', 1}; % point eval on cell
Nodal_Var(21).Data = {sym([(1/5); (3/5)]), 'eval_cell', 1}; % point eval on cell
elseif (deg_k==6)
Nodal_Var( 4).Data = {sym([(5/6); (1/6)]), 'eval_facet', 1}; % point eval on facet (edge) #1
Nodal_Var( 5).Data = {sym([(4/6); (2/6)]), 'eval_facet', 1}; % point eval on facet (edge) #1
Nodal_Var( 6).Data = {sym([(3/6); (3/6)]), 'eval_facet', 1}; % point eval on facet (edge) #1
Nodal_Var( 7).Data = {sym([(2/6); (4/6)]), 'eval_facet', 1}; % point eval on facet (edge) #1
Nodal_Var( 8).Data = {sym([(1/6); (5/6)]), 'eval_facet', 1}; % point eval on facet (edge) #1
Nodal_Var( 9).Data = {sym([0; (5/6)]), 'eval_facet', 2}; % point eval on facet (edge) #2
Nodal_Var(10).Data = {sym([0; (4/6)]), 'eval_facet', 2}; % point eval on facet (edge) #2
Nodal_Var(11).Data = {sym([0; (3/6)]), 'eval_facet', 2}; % point eval on facet (edge) #2
Nodal_Var(12).Data = {sym([0; (2/6)]), 'eval_facet', 2}; % point eval on facet (edge) #2
Nodal_Var(13).Data = {sym([0; (1/6)]), 'eval_facet', 2}; % point eval on facet (edge) #2
Nodal_Var(14).Data = {sym([(1/6); 0]), 'eval_facet', 3}; % point eval on facet (edge) #3
Nodal_Var(15).Data = {sym([(2/6); 0]), 'eval_facet', 3}; % point eval on facet (edge) #3
Nodal_Var(16).Data = {sym([(3/6); 0]), 'eval_facet', 3}; % point eval on facet (edge) #3
Nodal_Var(17).Data = {sym([(4/6); 0]), 'eval_facet', 3}; % point eval on facet (edge) #3
Nodal_Var(18).Data = {sym([(5/6); 0]), 'eval_facet', 3}; % point eval on facet (edge) #3
Nodal_Var(19).Data = {sym([(3/6); (2/6)]), 'eval_cell', 1}; % point eval on cell
Nodal_Var(20).Data = {sym([(2/6); (3/6)]), 'eval_cell', 1}; % point eval on cell
Nodal_Var(21).Data = {sym([(1/6); (1/6)]), 'eval_cell', 1}; % point eval on cell
Nodal_Var(22).Data = {sym([(1/6); (3/6)]), 'eval_cell', 1}; % point eval on cell
Nodal_Var(23).Data = {sym([(1/6); (2/6)]), 'eval_cell', 1}; % point eval on cell
Nodal_Var(24).Data = {sym([(4/6); (1/6)]), 'eval_cell', 1}; % point eval on cell
Nodal_Var(25).Data = {sym([(2/6); (1/6)]), 'eval_cell', 1}; % point eval on cell
Nodal_Var(26).Data = {sym([(3/6); (1/6)]), 'eval_cell', 1}; % point eval on cell
Nodal_Var(27).Data = {sym([(1/6); (4/6)]), 'eval_cell', 1}; % point eval on cell
Nodal_Var(28).Data = {sym([(1/3); (1/3)]), 'eval_cell', 1}; % point eval on cell
else
error('Not implemented!');
end
end
end
end
function Nodal_Var = lagrange_nodal_points_3D(deg_k)
% lay out the points on the reference tetrahedron, starting with the vertices
% (for degree k >= 1). For degree k = 0, just the barycenter.
NV = nchoosek(3 + deg_k,deg_k);
Nodal_Var(NV).Data = [];
% define nodal variable data (in order of the DoF index)
% these specify what the Degrees-of-Freedom (DoFs) are
% Note: these involve point evaluations (reference coordinates are given)
if (deg_k==0)
Nodal_Var(1).Data = {sym([(1/4); (1/4); (1/4)]), 'eval_cell', 1}; % point eval on cell
else
Nodal_Var(1).Data = {sym([0; 0; 0]), 'eval_vertex', 1}; % point eval on vertex #1
Nodal_Var(2).Data = {sym([1; 0; 0]), 'eval_vertex', 2}; % point eval on vertex #2
Nodal_Var(3).Data = {sym([0; 1; 0]), 'eval_vertex', 3}; % point eval on vertex #3
Nodal_Var(4).Data = {sym([0; 0; 1]), 'eval_vertex', 4}; % point eval on vertex #4
% now allocate the rest on the facets and the cell
if NV >= 5
if (deg_k==2)
Nodal_Var( 5).Data = {sym([(1/2); 0; 0]), 'eval_edge', 1}; % point eval on edge #1
Nodal_Var( 6).Data = {sym([0; (1/2); 0]), 'eval_edge', 2}; % point eval on edge #2
Nodal_Var( 7).Data = {sym([0; 0; (1/2)]), 'eval_edge', 3}; % point eval on edge #3
Nodal_Var( 8).Data = {sym([(1/2); (1/2); 0]), 'eval_edge', 4}; % point eval on edge #4
Nodal_Var( 9).Data = {sym([0; (1/2); (1/2)]), 'eval_edge', 5}; % point eval on edge #5
Nodal_Var(10).Data = {sym([(1/2); 0; (1/2)]), 'eval_edge', 6}; % point eval on edge #6
elseif (deg_k==3)
Nodal_Var( 5).Data = {sym([(1/3); 0; 0]), 'eval_edge', 1}; % point eval on edge #1
Nodal_Var( 6).Data = {sym([(2/3); 0; 0]), 'eval_edge', 1}; % point eval on edge #1
Nodal_Var( 7).Data = {sym([0; (1/3); 0]), 'eval_edge', 2}; % point eval on edge #2
Nodal_Var( 8).Data = {sym([0; (2/3); 0]), 'eval_edge', 2}; % point eval on edge #2
Nodal_Var( 9).Data = {sym([0; 0; (1/3)]), 'eval_edge', 3}; % point eval on edge #3
Nodal_Var(10).Data = {sym([0; 0; (2/3)]), 'eval_edge', 3}; % point eval on edge #3
Nodal_Var(11).Data = {sym([(2/3); (1/3); 0]), 'eval_edge', 4}; % point eval on edge #4
Nodal_Var(12).Data = {sym([(1/3); (2/3); 0]), 'eval_edge', 4}; % point eval on edge #4
Nodal_Var(13).Data = {sym([0; (2/3); (1/3)]), 'eval_edge', 5}; % point eval on edge #5
Nodal_Var(14).Data = {sym([0; (1/3); (2/3)]), 'eval_edge', 5}; % point eval on edge #5
Nodal_Var(15).Data = {sym([(1/3); 0; (2/3)]), 'eval_edge', 6}; % point eval on edge #6
Nodal_Var(16).Data = {sym([(2/3); 0; (1/3)]), 'eval_edge', 6}; % point eval on edge #6
Nodal_Var(17).Data = {sym([(1/3); (1/3); (1/3)]), 'eval_facet', 1}; % point eval on facet (face) #1
Nodal_Var(18).Data = {sym([ 0; (1/3); (1/3)]), 'eval_facet', 2}; % point eval on facet (face) #2
Nodal_Var(19).Data = {sym([(1/3); 0; (1/3)]), 'eval_facet', 3}; % point eval on facet (face) #3
Nodal_Var(20).Data = {sym([(1/3); (1/3); 0]), 'eval_facet', 4}; % point eval on facet (face) #4
elseif (deg_k==4)
Nodal_Var( 5).Data = {sym([(1/4); 0; 0]), 'eval_edge', 1}; % point eval on edge #1
Nodal_Var( 6).Data = {sym([(1/2); 0; 0]), 'eval_edge', 1}; % point eval on edge #1
Nodal_Var( 7).Data = {sym([(3/4); 0; 0]), 'eval_edge', 1}; % point eval on edge #1
Nodal_Var( 8).Data = {sym([0; (1/4); 0]), 'eval_edge', 2}; % point eval on edge #2
Nodal_Var( 9).Data = {sym([0; (1/2); 0]), 'eval_edge', 2}; % point eval on edge #2
Nodal_Var(10).Data = {sym([0; (3/4); 0]), 'eval_edge', 2}; % point eval on edge #2
Nodal_Var(11).Data = {sym([0; 0; (1/4)]), 'eval_edge', 3}; % point eval on edge #3
Nodal_Var(12).Data = {sym([0; 0; (1/2)]), 'eval_edge', 3}; % point eval on edge #3
Nodal_Var(13).Data = {sym([0; 0; (3/4)]), 'eval_edge', 3}; % point eval on edge #3
Nodal_Var(14).Data = {sym([(3/4); (1/4); 0]), 'eval_edge', 4}; % point eval on edge #4
Nodal_Var(15).Data = {sym([(1/2); (1/2); 0]), 'eval_edge', 4}; % point eval on edge #4
Nodal_Var(16).Data = {sym([(1/4); (3/4); 0]), 'eval_edge', 4}; % point eval on edge #4
Nodal_Var(17).Data = {sym([0; (3/4); (1/4)]), 'eval_edge', 5}; % point eval on edge #5
Nodal_Var(18).Data = {sym([0; (1/2); (1/2)]), 'eval_edge', 5}; % point eval on edge #5
Nodal_Var(19).Data = {sym([0; (1/4); (3/4)]), 'eval_edge', 5}; % point eval on edge #5
Nodal_Var(20).Data = {sym([(1/4); 0; (3/4)]), 'eval_edge', 6}; % point eval on edge #6
Nodal_Var(21).Data = {sym([(1/2); 0; (1/2)]), 'eval_edge', 6}; % point eval on edge #6
Nodal_Var(22).Data = {sym([(3/4); 0; (1/4)]), 'eval_edge', 6}; % point eval on edge #6
Nodal_Var(23).Data = {sym([(1/2); (1/4); (1/4)]), 'eval_facet', 1}; % point eval on facet (face) #1
Nodal_Var(24).Data = {sym([(1/4); (1/2); (1/4)]), 'eval_facet', 1}; % point eval on facet (face) #1
Nodal_Var(25).Data = {sym([(1/4); (1/4); (1/2)]), 'eval_facet', 1}; % point eval on facet (face) #1
Nodal_Var(26).Data = {sym([ 0; (1/4); (1/4)]), 'eval_facet', 2}; % point eval on facet (face) #2
Nodal_Var(27).Data = {sym([ 0; (1/4); (1/2)]), 'eval_facet', 2}; % point eval on facet (face) #2
Nodal_Var(28).Data = {sym([ 0; (1/2); (1/4)]), 'eval_facet', 2}; % point eval on facet (face) #2
Nodal_Var(29).Data = {sym([(1/4); 0; (1/4)]), 'eval_facet', 3}; % point eval on facet (face) #3
Nodal_Var(30).Data = {sym([(1/2); 0; (1/4)]), 'eval_facet', 3}; % point eval on facet (face) #3
Nodal_Var(31).Data = {sym([(1/4); 0; (1/2)]), 'eval_facet', 3}; % point eval on facet (face) #3
Nodal_Var(32).Data = {sym([(1/4); (1/4); 0]), 'eval_facet', 4}; % point eval on facet (face) #4
Nodal_Var(33).Data = {sym([(1/4); (1/2); 0]), 'eval_facet', 4}; % point eval on facet (face) #4
Nodal_Var(34).Data = {sym([(1/2); (1/4); 0]), 'eval_facet', 4}; % point eval on facet (face) #4
Nodal_Var(35).Data = {sym([(1/4); (1/4); (1/4)]), 'eval_cell', 1}; % point eval on cell
elseif (deg_k==5)
Nodal_Var( 5).Data = {sym([(1/5); 0; 0]), 'eval_edge', 1}; % point eval on edge #1
Nodal_Var( 6).Data = {sym([(2/5); 0; 0]), 'eval_edge', 1}; % point eval on edge #1
Nodal_Var( 7).Data = {sym([(3/5); 0; 0]), 'eval_edge', 1}; % point eval on edge #1
Nodal_Var( 8).Data = {sym([(4/5); 0; 0]), 'eval_edge', 1}; % point eval on edge #1
Nodal_Var( 9).Data = {sym([0; (1/5); 0]), 'eval_edge', 2}; % point eval on edge #2
Nodal_Var(10).Data = {sym([0; (2/5); 0]), 'eval_edge', 2}; % point eval on edge #2
Nodal_Var(11).Data = {sym([0; (3/5); 0]), 'eval_edge', 2}; % point eval on edge #2
Nodal_Var(12).Data = {sym([0; (4/5); 0]), 'eval_edge', 2}; % point eval on edge #2
Nodal_Var(13).Data = {sym([0; 0; (1/5)]), 'eval_edge', 3}; % point eval on edge #3
Nodal_Var(14).Data = {sym([0; 0; (2/5)]), 'eval_edge', 3}; % point eval on edge #3
Nodal_Var(15).Data = {sym([0; 0; (3/5)]), 'eval_edge', 3}; % point eval on edge #3
Nodal_Var(16).Data = {sym([0; 0; (4/5)]), 'eval_edge', 3}; % point eval on edge #3
Nodal_Var(17).Data = {sym([(4/5); (1/5); 0]), 'eval_edge', 4}; % point eval on edge #4
Nodal_Var(18).Data = {sym([(3/5); (2/5); 0]), 'eval_edge', 4}; % point eval on edge #4
Nodal_Var(19).Data = {sym([(2/5); (3/5); 0]), 'eval_edge', 4}; % point eval on edge #4
Nodal_Var(20).Data = {sym([(1/5); (4/5); 0]), 'eval_edge', 4}; % point eval on edge #4
Nodal_Var(21).Data = {sym([0; (4/5); (1/5)]), 'eval_edge', 5}; % point eval on edge #5
Nodal_Var(22).Data = {sym([0; (3/5); (2/5)]), 'eval_edge', 5}; % point eval on edge #5
Nodal_Var(23).Data = {sym([0; (2/5); (3/5)]), 'eval_edge', 5}; % point eval on edge #5
Nodal_Var(24).Data = {sym([0; (1/5); (4/5)]), 'eval_edge', 5}; % point eval on edge #5
Nodal_Var(25).Data = {sym([(1/5); 0; (4/5)]), 'eval_edge', 6}; % point eval on edge #6
Nodal_Var(26).Data = {sym([(2/5); 0; (3/5)]), 'eval_edge', 6}; % point eval on edge #6
Nodal_Var(27).Data = {sym([(3/5); 0; (2/5)]), 'eval_edge', 6}; % point eval on edge #6
Nodal_Var(28).Data = {sym([(4/5); 0; (1/5)]), 'eval_edge', 6}; % point eval on edge #6
%%%%%%%%%%%
Nodal_Var(29).Data = {sym([(1/5); (2/5); (2/5)]), 'eval_facet', 1}; % point eval on facet (face) #1
Nodal_Var(30).Data = {sym([(3/5); (1/5); (1/5)]), 'eval_facet', 1}; % point eval on facet (face) #1
Nodal_Var(31).Data = {sym([(2/5); (1/5); (2/5)]), 'eval_facet', 1}; % point eval on facet (face) #1
Nodal_Var(32).Data = {sym([(1/5); (3/5); (1/5)]), 'eval_facet', 1}; % point eval on facet (face) #1
Nodal_Var(33).Data = {sym([(2/5); (2/5); (1/5)]), 'eval_facet', 1}; % point eval on facet (face) #1
Nodal_Var(34).Data = {sym([(1/5); (1/5); (3/5)]), 'eval_facet', 1}; % point eval on facet (face) #1
%%%%%%%%%%%
Nodal_Var(35).Data = {sym([ 0; (2/5); (2/5)]), 'eval_facet', 2}; % point eval on facet (face) #2
Nodal_Var(36).Data = {sym([ 0; (1/5); (1/5)]), 'eval_facet', 2}; % point eval on facet (face) #2
Nodal_Var(37).Data = {sym([ 0; (2/5); (1/5)]), 'eval_facet', 2}; % point eval on facet (face) #2
Nodal_Var(38).Data = {sym([ 0; (1/5); (3/5)]), 'eval_facet', 2}; % point eval on facet (face) #2
Nodal_Var(39).Data = {sym([ 0; (1/5); (2/5)]), 'eval_facet', 2}; % point eval on facet (face) #2
Nodal_Var(40).Data = {sym([ 0; (3/5); (1/5)]), 'eval_facet', 2}; % point eval on facet (face) #2
%%%%%%%%%%%
Nodal_Var(41).Data = {sym([(2/5); 0; (2/5)]), 'eval_facet', 3}; % point eval on facet (face) #3
Nodal_Var(42).Data = {sym([(1/5); 0; (1/5)]), 'eval_facet', 3}; % point eval on facet (face) #3
Nodal_Var(43).Data = {sym([(1/5); 0; (2/5)]), 'eval_facet', 3}; % point eval on facet (face) #3
Nodal_Var(44).Data = {sym([(3/5); 0; (1/5)]), 'eval_facet', 3}; % point eval on facet (face) #3
Nodal_Var(45).Data = {sym([(2/5); 0; (1/5)]), 'eval_facet', 3}; % point eval on facet (face) #3
Nodal_Var(46).Data = {sym([(1/5); 0; (3/5)]), 'eval_facet', 3}; % point eval on facet (face) #3
%%%%%%%%%%%
Nodal_Var(47).Data = {sym([(2/5); (2/5); 0]), 'eval_facet', 4}; % point eval on facet (face) #4
Nodal_Var(48).Data = {sym([(1/5); (1/5); 0]), 'eval_facet', 4}; % point eval on facet (face) #4
Nodal_Var(49).Data = {sym([(2/5); (1/5); 0]), 'eval_facet', 4}; % point eval on facet (face) #4
Nodal_Var(50).Data = {sym([(1/5); (3/5); 0]), 'eval_facet', 4}; % point eval on facet (face) #4
Nodal_Var(51).Data = {sym([(1/5); (2/5); 0]), 'eval_facet', 4}; % point eval on facet (face) #4
Nodal_Var(52).Data = {sym([(3/5); (1/5); 0]), 'eval_facet', 4}; % point eval on facet (face) #4
%%%%%
Nodal_Var(53).Data = {sym([(1/5); (1/5); (1/5)]), 'eval_cell', 1}; % point eval on cell
Nodal_Var(54).Data = {sym([(2/5); (1/5); (1/5)]), 'eval_cell', 1}; % point eval on cell
Nodal_Var(55).Data = {sym([(1/5); (2/5); (1/5)]), 'eval_cell', 1}; % point eval on cell
Nodal_Var(56).Data = {sym([(1/5); (1/5); (2/5)]), 'eval_cell', 1}; % point eval on cell
else
error('Not implemented!');
end
end
end
end
|
github
|
eardi/sm-fpca-master
|
Generate_RaviartThomas_Element_File.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Elem_Defn/Generators/Generate_RaviartThomas_Element_File.m
| 15,235 |
utf_8
|
e329cf81684aa6dad279d26b7fbf4d66
|
function status = Generate_RaviartThomas_Element_File(Element_Domain,Degree_k,Output_Dir)
%Generate_RaviartThomas_Element_File
%
% This generates a finite element reference m-file that defines a
% particular Raviart-Thomas element of given fixed degree on a given
% reference domain.
%
% The inputs are:
% Element_Domain = 'interval', 'triangle', 'tetrahedron', etc.
% Degree_k = polynomial degree of finite element.
% Output_Dir = string specifying where to write the file.
% Copyright (c) 10-10-2016, Shawn W. Walker
% get basic info text
[Element_Domain, Domain_STR, Domain_Fig_ASCII, Dim] = setup_generic_element_file_text(Element_Domain);
ENDL = '\n';
TAB = ' ';
%TAB2 = [TAB, TAB];
%TAB3 = [TAB2, TAB];
%TAB4 = [TAB3, TAB];
% get the (reference) finite element space
if strcmpi(Element_Domain,'interval')
error('Invalid domain!');
elseif strcmpi(Element_Domain,'triangle')
[Nodal_Basis, Nodal_Var] = Get_RaviartThomas_On_Simplex(Dim,Degree_k);
elseif strcmpi(Element_Domain,'tetrahedron')
[Nodal_Basis, Nodal_Var] = Get_RaviartThomas_On_Simplex(Dim,Degree_k);
else
error('Not implemented!');
end
% setup filename
Degree_str = num2str(Degree_k);
Dim_str = num2str(Dim);
FuncName = ['raviart_thomas_deg', Degree_str, '_dim', Dim_str];
Output_FileName = fullfile(Output_Dir, [FuncName, '.m']);
% open file for writing
fid = fopen(Output_FileName, 'w');
% define write line function
write_line = @(STR) fprintf(fid, [STR, ENDL]);
write_string = @(STR) fprintf(fid, STR);
% write header
write_line(['', 'function Elem = ', FuncName, '(Type_STR)']);
write_line(['%%', FuncName]);
write_line(['%%']);
write_line(['%%', TAB, 'This defines a reference finite element to be used by FELICITY.']);
write_line(['%%', TAB, 'INPUT: string = ''CG''/''DG'' (continuous/DIScontinuous galerkin).']);
write_line(['%%']);
write_line(['%%', TAB, 'Raviart-Thomas H(div) Finite Element of degree = ', Degree_str, ', in dimension = ', Dim_str, '.']);
write_line(['%%']);
write_line(['%%', TAB, 'Reference Domain: ', Domain_STR, '.']);
write_line(['%%']);
write_string([Domain_Fig_ASCII]);
write_line(['%%']);
write_line(['%%', TAB, 'The basis functions are vector-valued (number of components = topological dimension).']);
write_line(['%%']);
write_line(['%%', TAB, 'The basis functions associated with Degrees-of-Freedom (DoFs) on a facet']);
write_line(['%%', TAB, 'have an orientation dictated by the facet''s orientation.']);
write_line(['%%']);
write_line(['%%', TAB, 'For simplicity, the basis functions specified in this file assume a']);
write_line(['%%', TAB, 'fixed orientation on the reference element, which is that all facets']);
write_line(['%%', TAB, 'are oriented with the normal vector pointing *OUT* of the reference']);
write_line(['%%', TAB, 'element.']);
write_line(['%%']);
write_line(['%%', TAB, 'Thus, one needs to introduce appropriate +/- sign changes when mapping']);
write_line(['%%', TAB, 'these basis functions to the *actual* element in the mesh. This is']);
write_line(['%%', TAB, 'handled by the "guts" of FELICITY to auto-generate code to take care of']);
write_line(['%%', TAB, 'these sign changes (e.g. when assembling matrices, interpolation, etc.).']);
write_line(['%%', TAB, 'Note: only sign changes are made; there is no permuting of DoFs.']);
% This is **not** the case with H(curl) elements!
write_line(['']);
current_date = date;
write_line(['%%', ' Copyright (c) ', current_date, ', Shawn W. Walker']);
write_line(['']);
write_line(['%% name it!']);
write_line(['Elem.Name = mfilename;']);
write_line(['']);
write_line(['%% determine continuous or discontinuous galerkin space']);
write_line(['if (nargin==0)']);
write_line([TAB, 'Type_STR = ''CG''; %% default']);
write_line(['end']);
write_line(['if strcmpi(Type_STR,''cg'')']);
write_line([TAB, 'Elem.Type = ''CG'';']);
write_line(['elseif strcmpi(Type_STR,''dg'')']);
write_line([TAB, 'Elem.Type = ''DG'';']);
write_line(['else']);
write_line([TAB, 'error(''Invalid input type! Must be ''''CG'''' or ''''DG''''.'');']);
write_line(['end']);
write_line(['']);
write_line(['%% topological dimension and domain']);
write_line(['Elem.Dim = ', Dim_str, ';']);
write_line(['Elem.Domain = ''', Element_Domain, ''';']);
write_line(['']);
write_line(['%% nodal basis function definitions (in the order of their local Degree-of-Freedom index)']);
Num_Basis = length(Nodal_Basis);
write_line(['Elem.Basis(', num2str(Num_Basis), ').Func = []; %% init']);
% loop through nodal basis
for ii = 1:length(Nodal_Basis)
BF = Nodal_Basis(ii).Func;
Basis_Func_Str = write_element_file_basis_func_string(BF);
write_line(['Elem.Basis(', num2str(ii), ').Func = {', Basis_Func_Str, '};']);
end
write_line(['%% local mapping transformation to use']);
Transformation_Type_str = 'Hdiv_Trans';
write_line(['Elem.Transformation = ''', Transformation_Type_str, ''';']);
write_line(['Elem.Degree = ', Degree_str, ';']);
write_line(['']);
write_line(['%% nodal variable data (in the order of their local Degree-of-Freedom index)']);
write_line(['%% (the nodal point is given in barycentric coordinates)']);
Num_Nodal_Var = length(Nodal_Var);
write_line(['Elem.Nodal_Var(', num2str(Num_Nodal_Var), ').Data = []; %% init']);
% loop through nodal variables
for ii = 1:length(Nodal_Var)
NV = Nodal_Var(ii).Data;
Nodal_BC_str = write_element_file_barycentric_string(NV{1});
% write Raviart-Thomas element nodal variable data string
if strcmpi(NV{3},'int_facet')
Dual_Basis_str = ['[', char(NV{2}), ']'];
Nodal_Var_Data_str = ['{', Nodal_BC_str, ', ''', Dual_Basis_str, ''', ''', NV{3}, ''', ', num2str(NV{4}), '}'];
elseif strcmpi(NV{3},'int_cell')
% generate string for dual basis function
BF = NV{2};
if (Dim==2)
DB_1 = char(BF(1));
DB_2 = char(BF(2));
Dual_Basis_str = ['[', DB_1, '; ', DB_2, ']'];
elseif (Dim==3)
DB_1 = char(BF(1));
DB_2 = char(BF(2));
DB_3 = char(BF(3));
Dual_Basis_str = ['[', DB_1, '; ', DB_2, '; ', DB_3, ']'];
elseif (Dim==1)
error('Invalid!');
else
error('Not implemented!');
end
Nodal_Var_Data_str = ['{', Nodal_BC_str, ', ''', Dual_Basis_str, ''', ''', NV{3}, ''', ',...
num2str(NV{4}), ', ''', NV{5}, ''', ', num2str(NV{6}), '}'];
else
error('Invalid!');
end
write_line(['Elem.Nodal_Var(', num2str(ii), ').Data = ', Nodal_Var_Data_str, ';']);
end
write_line(['']);
write_line(['%%%%%%%%%% topological arrangement of nodal points %%%%%%%%%%']);
write_line(['%% note: multiple sets of nodal variables can be associated with each topological entity.']);
write_line(['%% This is done by defining multiple matrix arrays within each matlab cell.']);
write_line(['%% See the FELICITY manual for more info.']);
write_line(['']);
Nodal_Top = get_nodal_top_arrangement(Element_Domain,Nodal_Var);
DoF_TAB = ' ';
write_line(['%% nodes attached to vertices']);
if ~isempty(Nodal_Top.V{1})
write_line(['Elem.Nodal_Top.V = {...']);
Nodal_Sets_str = write_element_file_nodal_top_string(Nodal_Top.V,DoF_TAB);
write_line(Nodal_Sets_str);
write_line([DoF_TAB, '};']);
write_line(['%%']);
else
write_line(['Elem.Nodal_Top.V = {[]};']);
end
write_line(['']);
write_line(['%% nodes attached to edges']);
if ~isempty(Nodal_Top.E{1})
write_line(['Elem.Nodal_Top.E = {...']);
Nodal_Sets_str = write_element_file_nodal_top_string(Nodal_Top.E,DoF_TAB);
write_line(Nodal_Sets_str);
write_line([DoF_TAB, '};']);
write_line(['%%']);
else
write_line(['Elem.Nodal_Top.E = {[]};']);
end
write_line(['']);
write_line(['%% nodes attached to triangles (faces)']);
if ~isempty(Nodal_Top.F{1})
write_line(['Elem.Nodal_Top.F = {...']);
Nodal_Sets_str = write_element_file_nodal_top_string(Nodal_Top.F,DoF_TAB);
write_line(Nodal_Sets_str);
write_line([DoF_TAB, '};']);
write_line(['%%']);
else
write_line(['Elem.Nodal_Top.F = {[]};']);
end
write_line(['']);
write_line(['%% nodes attached to tetrahedra (cells)']);
if ~isempty(Nodal_Top.T{1})
write_line(['Elem.Nodal_Top.T = {...']);
Nodal_Sets_str = write_element_file_nodal_top_string(Nodal_Top.T,DoF_TAB);
write_line(Nodal_Sets_str);
write_line([DoF_TAB, '};']);
write_line(['%%']);
else
write_line(['Elem.Nodal_Top.T = {[]};']);
end
write_line(['']);
write_string(['end']);
% DONE!
status = fclose(fid);
end
function Nodal_Top = get_nodal_top_arrangement(Element_Domain,Nodal_Var)
%
% This arranges the nodal variables (i.e. the nodal points) on their
% corresponding topological entities.
if strcmpi(Element_Domain,'interval')
% this is invalid!
Nodal_Top.V = {[]};
Nodal_Top.E = {[]};
Nodal_Top.F = {[]};
Nodal_Top.T = {[]};
elseif strcmpi(Element_Domain,'triangle')
% init
Edge1 = [];
Edge2 = [];
Edge3 = [];
Cell_1 = [];
Cell_2 = [];
for ind = 1:length(Nodal_Var)
NV = Nodal_Var(ind).Data;
Pt = NV{1};
BC_Pt = double(convert_to_barycentric(Pt))';
Type = NV{3};
Entity_Index = NV{4};
if strcmpi(Type,'int_facet')
if (Entity_Index==1)
Edge1 = [Edge1; ind, BC_Pt];
elseif (Entity_Index==2)
Edge2 = [Edge2; ind, BC_Pt];
elseif (Entity_Index==3)
Edge3 = [Edge3; ind, BC_Pt];
else
error('Invalid!');
end
elseif strcmpi(Type,'int_cell')
dof_set = NV{6};
if (dof_set==1)
Cell_1 = [Cell_1; ind, BC_Pt];
elseif (dof_set==2)
Cell_2 = [Cell_2; ind, BC_Pt];
else
error('Invalid!');
end
else
error('Invalid!');
end
end
Num_E1 = size(Edge1,1);
Num_E2 = size(Edge2,1);
Num_E3 = size(Edge3,1);
Num_C1 = size(Cell_1,1);
Num_C2 = size(Cell_2,1);
Num_DoF = Num_E1 + Num_E2 + Num_E3 + Num_C1 + Num_C2;
if (Num_DoF~=length(Nodal_Var))
error('Number of DoFs is incorrect!');
end
CHK_EDGE_DOF = max(abs([Num_E1, Num_E2, Num_E3] - Num_E1));
if (CHK_EDGE_DOF~=0)
error('Number of Edge DoFs on each edge is not the same!');
end
if (Num_C1~=Num_C2)
error('Number of Cell DoFs in each set is not the same!');
end
% there are no vertex DoFs
Nodal_Top.V = {[]};
% setup the facet (edge) DoFs
Edge1 = sortrows(Edge1,1); % sort based on DoF index
Edge2 = sortrows(Edge2,1);
Edge3 = sortrows(Edge3,1);
DoFs_on_Edge = [Edge1(:,1)'; Edge2(:,1)'; Edge3(:,1)'];
Nodal_Top.E = {DoFs_on_Edge};
% setup the cell (face) DoFs
if ~isempty(Cell_1)
Cell_1 = sortrows(Cell_1,1); % sort based on DoF index
Cell_2 = sortrows(Cell_2,1);
DoFs_on_Face_1 = [Cell_1(:,1)'];
DoFs_on_Face_2 = [Cell_2(:,1)'];
% there are 2 sets of DoFs (one for each vector component)
Nodal_Top.F = {DoFs_on_Face_1, DoFs_on_Face_2};
else
Nodal_Top.F = {[]};
end
% there are no other DoFs
Nodal_Top.T = {[]};
elseif strcmpi(Element_Domain,'tetrahedron')
% init
Face1 = [];
Face2 = [];
Face3 = [];
Face4 = [];
Cell_1 = [];
Cell_2 = [];
Cell_3 = [];
for ind = 1:length(Nodal_Var)
NV = Nodal_Var(ind).Data;
Pt = NV{1};
BC_Pt = double(convert_to_barycentric(Pt))';
Type = NV{3};
Entity_Index = NV{4};
if strcmpi(Type,'int_facet')
if (Entity_Index==1)
Face1 = [Face1; ind, BC_Pt];
elseif (Entity_Index==2)
Face2 = [Face2; ind, BC_Pt];
elseif (Entity_Index==3)
Face3 = [Face3; ind, BC_Pt];
elseif (Entity_Index==4)
Face4 = [Face4; ind, BC_Pt];
else
error('Invalid!');
end
elseif strcmpi(Type,'int_cell')
dof_set = NV{6};
if (dof_set==1)
Cell_1 = [Cell_1; ind, BC_Pt];
elseif (dof_set==2)
Cell_2 = [Cell_2; ind, BC_Pt];
elseif (dof_set==3)
Cell_3 = [Cell_3; ind, BC_Pt];
else
error('Invalid!');
end
else
error('Invalid!');
end
end
Num_F1 = size(Face1,1);
Num_F2 = size(Face2,1);
Num_F3 = size(Face3,1);
Num_F4 = size(Face4,1);
Num_C1 = size(Cell_1,1);
Num_C2 = size(Cell_2,1);
Num_C3 = size(Cell_3,1);
Num_DoF = Num_F1 + Num_F2 + Num_F3 + Num_F4 + ...
Num_C1 + Num_C2 + Num_C3;
if (Num_DoF~=length(Nodal_Var))
error('Number of DoFs is incorrect!');
end
CHK_FACE_DOF = max(abs([Num_F1, Num_F2, Num_F3, Num_F4] - Num_F1));
if (CHK_FACE_DOF~=0)
error('Number of Face DoFs on each face is not the same!');
end
CHK_CELL_DOF = max(abs([Num_C1, Num_C2, Num_C3] - Num_C1));
if (CHK_CELL_DOF~=0)
error('Number of Cell DoFs in each set is not the same!');
end
% there are no vertex DoFs
Nodal_Top.V = {[]};
% there are no edge DoFs
Nodal_Top.E = {[]};
% setup the facet (face) DoFs
Face1 = sortrows(Face1,1); % sort based on DoF index
Face2 = sortrows(Face2,1);
Face3 = sortrows(Face3,1);
Face4 = sortrows(Face4,1);
DoFs_on_Face = [Face1(:,1)'; Face2(:,1)'; Face3(:,1)'; Face4(:,1)'];
Nodal_Top.F = {DoFs_on_Face};
% setup the cell (tet) DoFs
if ~isempty(Cell_1)
Cell_1 = sortrows(Cell_1,1); % sort based on DoF index
Cell_2 = sortrows(Cell_2,1);
Cell_3 = sortrows(Cell_3,1);
DoFs_on_Cell_1 = [Cell_1(:,1)'];
DoFs_on_Cell_2 = [Cell_2(:,1)'];
DoFs_on_Cell_3 = [Cell_3(:,1)'];
% there are 3 sets of DoFs (one for each vector component)
Nodal_Top.T = {DoFs_on_Cell_1, DoFs_on_Cell_2, DoFs_on_Cell_3};
else
Nodal_Top.T = {[]};
end
else
error('Not implemented!');
end
Vtx_DoFs = [];
for ii = 1:length(Nodal_Top.V)
Vtx_DoFs = [Vtx_DoFs; Nodal_Top.V{ii}(:)];
end
Edge_DoFs = [];
for ii = 1:length(Nodal_Top.E)
Edge_DoFs = [Edge_DoFs; Nodal_Top.E{ii}(:)];
end
Face_DoFs = [];
for ii = 1:length(Nodal_Top.F)
Face_DoFs = [Face_DoFs; Nodal_Top.F{ii}(:)];
end
Tet_DoFs = [];
for ii = 1:length(Nodal_Top.T)
Tet_DoFs = [Tet_DoFs; Nodal_Top.T{ii}(:)];
end
All_DoFs = [Vtx_DoFs; Edge_DoFs; Face_DoFs; Tet_DoFs];
% final check
Unique_DoFs = unique(All_DoFs);
if (length(All_DoFs)~=length(Unique_DoFs))
error('Not all DoF indices are distinct!');
end
end
|
github
|
eardi/sm-fpca-master
|
Generate_Lagrange_Element_File.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Elem_Defn/Generators/Generate_Lagrange_Element_File.m
| 17,212 |
utf_8
|
42bdd40861f80585634d21c5ebcaaa44
|
function status = Generate_Lagrange_Element_File(Element_Domain,Degree_k,Output_Dir)
%Generate_Lagrange_Element_File
%
% This generates a finite element reference m-file that defines a
% particular Lagrange element of given fixed degree on a given reference
% domain.
%
% The inputs are:
% Element_Domain = 'interval', 'triangle', 'tetrahedron', etc.
% Degree_k = polynomial degree of finite element.
% Output_FileName = string specifying where to write the file.
% Copyright (c) 10-10-2016, Shawn W. Walker
% get basic info text
[Element_Domain, Domain_STR, Domain_Fig_ASCII, Dim] = setup_generic_element_file_text(Element_Domain);
ENDL = '\n';
TAB = ' ';
%TAB2 = [TAB, TAB];
%TAB3 = [TAB2, TAB];
%TAB4 = [TAB3, TAB];
% get the (reference) finite element space
if strcmpi(Element_Domain,'interval')
[Nodal_Basis, Nodal_Var] = Get_Lagrange_On_Simplex(Dim,Degree_k);
elseif strcmpi(Element_Domain,'triangle')
[Nodal_Basis, Nodal_Var] = Get_Lagrange_On_Simplex(Dim,Degree_k);
elseif strcmpi(Element_Domain,'tetrahedron')
[Nodal_Basis, Nodal_Var] = Get_Lagrange_On_Simplex(Dim,Degree_k);
else
error('Not implemented!');
end
% setup filename
Degree_str = num2str(Degree_k);
Dim_str = num2str(Dim);
FuncName = ['lagrange_deg', Degree_str, '_dim', Dim_str];
Output_FileName = fullfile(Output_Dir, [FuncName, '.m']);
% open file for writing
fid = fopen(Output_FileName, 'w');
% define write line function
write_line = @(STR) fprintf(fid, [STR, ENDL]);
write_string = @(STR) fprintf(fid, STR);
% write header
write_line(['', 'function Elem = ', FuncName, '(Type_STR)']);
write_line(['%%', FuncName]);
write_line(['%%']);
write_line(['%%', TAB, 'This defines a reference finite element to be used by FELICITY.']);
write_line(['%%', TAB, 'INPUT: string = ''CG''/''DG'' (continuous/DIScontinuous galerkin).']);
write_line(['%%']);
write_line(['%%', TAB, 'Lagrange H^1 Finite Element of degree = ', Degree_str, ', in dimension = ', Dim_str, '.']);
write_line(['%%']);
write_line(['%%', TAB, 'Reference Domain: ', Domain_STR, '.']);
write_line(['%%']);
write_line([Domain_Fig_ASCII]);
current_date = date;
write_line(['%%', ' Copyright (c) ', current_date, ', Shawn W. Walker']);
write_line(['']);
write_line(['%% name it!']);
write_line(['Elem.Name = mfilename;']);
write_line(['']);
if (Degree_k==0)
write_line(['%% space must be discontinuous galerkin for piecewise constant']);
write_line(['Elem.Type = ''DG'';']);
else
write_line(['%% determine continuous or discontinuous galerkin space']);
write_line(['if (nargin==0)']);
write_line([TAB, 'Type_STR = ''CG''; %% default']);
write_line(['end']);
write_line(['if strcmpi(Type_STR,''cg'')']);
write_line([TAB, 'Elem.Type = ''CG'';']);
write_line(['elseif strcmpi(Type_STR,''dg'')']);
write_line([TAB, 'Elem.Type = ''DG'';']);
write_line(['else']);
write_line([TAB, 'error(''Invalid input type! Must be ''''CG'''' or ''''DG''''.'');']);
write_line(['end']);
end
write_line(['']);
write_line(['%% topological dimension and domain']);
write_line(['Elem.Dim = ', Dim_str, ';']);
write_line(['Elem.Domain = ''', Element_Domain, ''';']);
write_line(['']);
write_line(['%% nodal basis function definitions (in the order of their local Degree-of-Freedom index)']);
Num_Basis = length(Nodal_Basis);
write_line(['Elem.Basis(', num2str(Num_Basis), ').Func = []; %% init']);
% loop through nodal basis
for ii = 1:length(Nodal_Basis)
BF = Nodal_Basis(ii).Func;
Basis_Func_Str = write_element_file_basis_func_string(BF);
write_line(['Elem.Basis(', num2str(ii), ').Func = {', Basis_Func_Str, '};']);
end
write_line(['%% local mapping transformation to use']);
Transformation_Type_str = 'H1_Trans';
write_line(['Elem.Transformation = ''', Transformation_Type_str, ''';']);
write_line(['Elem.Degree = ', Degree_str, ';']);
write_line(['']);
write_line(['%% nodal variable data (in the order of their local Degree-of-Freedom index)']);
write_line(['%% (the nodal point is given in barycentric coordinates)']);
Num_Nodal_Var = length(Nodal_Var);
write_line(['Elem.Nodal_Var(', num2str(Num_Nodal_Var), ').Data = []; %% init']);
% loop through nodal variables
for ii = 1:length(Nodal_Var)
NV = Nodal_Var(ii).Data;
Nodal_BC_str = write_element_file_barycentric_string(NV{1});
% write Lagrange element nodal variable data string
Nodal_Var_Data_str = ['{', Nodal_BC_str, ', ''', NV{2}, ''', ', num2str(NV{3}), '}'];
write_line(['Elem.Nodal_Var(', num2str(ii), ').Data = ', Nodal_Var_Data_str, ';']);
end
write_line(['']);
write_line(['%%%%%%%%%% topological arrangement of nodal points %%%%%%%%%%']);
write_line(['%% note: multiple sets of nodal variables can be associated with each topological entity.']);
write_line(['%% This is done by defining multiple matrix arrays within each matlab cell.']);
write_line(['%% See the FELICITY manual for more info.']);
write_line(['']);
Nodal_Top = get_nodal_top_arrangement(Element_Domain,Nodal_Var);
DoF_TAB = ' ';
write_line(['%% nodes attached to vertices']);
if ~isempty(Nodal_Top.V{1})
write_line(['Elem.Nodal_Top.V = {...']);
Nodal_Sets_str = write_element_file_nodal_top_string(Nodal_Top.V,DoF_TAB);
write_line(Nodal_Sets_str);
write_line([DoF_TAB, '};']);
write_line(['%%']);
else
write_line(['Elem.Nodal_Top.V = {[]};']);
end
write_line(['']);
write_line(['%% nodes attached to edges']);
if ~isempty(Nodal_Top.E{1})
write_line(['Elem.Nodal_Top.E = {...']);
Nodal_Sets_str = write_element_file_nodal_top_string(Nodal_Top.E,DoF_TAB);
write_line(Nodal_Sets_str);
write_line([DoF_TAB, '};']);
write_line(['%%']);
else
write_line(['Elem.Nodal_Top.E = {[]};']);
end
write_line(['']);
write_line(['%% nodes attached to triangles (faces)']);
if ~isempty(Nodal_Top.F{1})
write_line(['Elem.Nodal_Top.F = {...']);
Nodal_Sets_str = write_element_file_nodal_top_string(Nodal_Top.F,DoF_TAB);
write_line(Nodal_Sets_str);
write_line([DoF_TAB, '};']);
write_line(['%%']);
else
write_line(['Elem.Nodal_Top.F = {[]};']);
end
write_line(['']);
write_line(['%% nodes attached to tetrahedra (cells)']);
if ~isempty(Nodal_Top.T{1})
write_line(['Elem.Nodal_Top.T = {...']);
Nodal_Sets_str = write_element_file_nodal_top_string(Nodal_Top.T,DoF_TAB);
write_line(Nodal_Sets_str);
write_line([DoF_TAB, '};']);
write_line(['%%']);
else
write_line(['Elem.Nodal_Top.T = {[]};']);
end
write_line(['']);
write_string(['end']);
% DONE!
status = fclose(fid);
end
function Nodal_Top = get_nodal_top_arrangement(Element_Domain,Nodal_Var)
%
% This arranges the nodal variables (i.e. the nodal points) on their
% corresponding topological entities.
if strcmpi(Element_Domain,'interval')
% init
Vtx1 = [];
Vtx2 = [];
Edge1 = [];
for ind = 1:length(Nodal_Var)
NV = Nodal_Var(ind).Data;
Pt = NV{1};
BC_Pt = double(convert_to_barycentric(Pt))';
Type = NV{2};
Entity_Index = NV{3};
if strcmpi(Type,'eval_vertex')
if (Entity_Index==1)
Vtx1 = [Vtx1; ind, BC_Pt];
elseif (Entity_Index==2)
Vtx2 = [Vtx2; ind, BC_Pt];
else
error('Invalid!');
end
elseif strcmpi(Type,'eval_cell')
Edge1 = [Edge1; ind, BC_Pt];
else
error('Invalid!');
end
end
Num_V1 = size(Vtx1,1);
Num_V2 = size(Vtx2,1);
Num_E1 = size(Edge1,1);
Num_DoF = Num_V1 + Num_V2 + Num_E1;
if (Num_DoF~=length(Nodal_Var))
error('Number of DoFs is incorrect!');
end
if (Num_V1~=Num_V2)
error('Number of Vtx DoFs at each vertex is not the same!');
end
% setup the vertex DoFs
if ~isempty(Vtx1)
Vtx1 = sortrows(Vtx1,1); % sort based on DoF index
Vtx2 = sortrows(Vtx2,1);
DoFs_on_Vtx = [Vtx1(:,1)'; Vtx2(:,1)'];
Nodal_Top.V = {DoFs_on_Vtx};
else
DoFs_on_Vtx = [];
end
Nodal_Top.V = {DoFs_on_Vtx};
% setup the cell (edge) DoFs
if ~isempty(Edge1)
Edge1 = sortrows(Edge1,1); % sort based on DoF index
DoFs_on_Edge = [Edge1(:,1)'];
else
DoFs_on_Edge = [];
end
Nodal_Top.E = {DoFs_on_Edge};
% there are no other DoFs
Nodal_Top.F = {[]};
Nodal_Top.T = {[]};
elseif strcmpi(Element_Domain,'triangle')
% init
Vtx1 = [];
Vtx2 = [];
Vtx3 = [];
Edge1 = [];
Edge2 = [];
Edge3 = [];
Face1 = [];
for ind = 1:length(Nodal_Var)
NV = Nodal_Var(ind).Data;
Pt = NV{1};
BC_Pt = double(convert_to_barycentric(Pt))';
Type = NV{2};
Entity_Index = NV{3};
if strcmpi(Type,'eval_vertex')
if (Entity_Index==1)
Vtx1 = [Vtx1; ind, BC_Pt];
elseif (Entity_Index==2)
Vtx2 = [Vtx2; ind, BC_Pt];
elseif (Entity_Index==3)
Vtx3 = [Vtx3; ind, BC_Pt];
else
error('Invalid!');
end
elseif strcmpi(Type,'eval_facet')
if (Entity_Index==1)
Edge1 = [Edge1; ind, BC_Pt];
elseif (Entity_Index==2)
Edge2 = [Edge2; ind, BC_Pt];
elseif (Entity_Index==3)
Edge3 = [Edge3; ind, BC_Pt];
else
error('Invalid!');
end
elseif strcmpi(Type,'eval_cell')
Face1 = [Face1; ind, BC_Pt];
else
error('Invalid!');
end
end
Num_V1 = size(Vtx1,1);
Num_V2 = size(Vtx2,1);
Num_V3 = size(Vtx3,1);
Num_E1 = size(Edge1,1);
Num_E2 = size(Edge2,1);
Num_E3 = size(Edge3,1);
Num_F1 = size(Face1,1);
Num_DoF = Num_V1 + Num_V2 + Num_V3 + Num_E1 + Num_E2 + Num_E3 + Num_F1;
if (Num_DoF~=length(Nodal_Var))
error('Number of DoFs is incorrect!');
end
CHK_VTX_DOF = max(abs([Num_V1, Num_V2, Num_V3] - Num_V1));
if (CHK_VTX_DOF~=0)
error('Number of Vtx DoFs at each vertex is not the same!');
end
CHK_EDGE_DOF = max(abs([Num_E1, Num_E2, Num_E3] - Num_E1));
if (CHK_EDGE_DOF~=0)
error('Number of Edge DoFs on each edge is not the same!');
end
% setup the vertex DoFs
if ~isempty(Vtx1)
Vtx1 = sortrows(Vtx1,1); % sort based on DoF index
Vtx2 = sortrows(Vtx2,1);
Vtx3 = sortrows(Vtx3,1);
DoFs_on_Vtx = [Vtx1(:,1)'; Vtx2(:,1)'; Vtx3(:,1)'];
else
DoFs_on_Vtx = [];
end
Nodal_Top.V = {DoFs_on_Vtx};
% setup the facet (edge) DoFs
if ~isempty(Edge1)
Edge1 = sortrows(Edge1,1); % sort based on DoF index
Edge2 = sortrows(Edge2,1);
Edge3 = sortrows(Edge3,1);
DoFs_on_Edge = [Edge1(:,1)'; Edge2(:,1)'; Edge3(:,1)'];
else
DoFs_on_Edge = [];
end
Nodal_Top.E = {DoFs_on_Edge};
% setup the cell (face) DoFs
if ~isempty(Face1)
Face1 = sortrows(Face1,1); % sort based on DoF index
DoFs_on_Face = [Face1(:,1)'];
else
DoFs_on_Face = [];
end
Nodal_Top.F = {DoFs_on_Face};
% there are no other DoFs
Nodal_Top.T = {[]};
elseif strcmpi(Element_Domain,'tetrahedron')
% init
Vtx1 = [];
Vtx2 = [];
Vtx3 = [];
Vtx4 = [];
Edge1 = [];
Edge2 = [];
Edge3 = [];
Edge4 = [];
Edge5 = [];
Edge6 = [];
Face1 = [];
Face2 = [];
Face3 = [];
Face4 = [];
Tet1 = [];
for ind = 1:length(Nodal_Var)
NV = Nodal_Var(ind).Data;
Pt = NV{1};
BC_Pt = double(convert_to_barycentric(Pt))';
Type = NV{2};
Entity_Index = NV{3};
if strcmpi(Type,'eval_vertex')
if (Entity_Index==1)
Vtx1 = [Vtx1; ind, BC_Pt];
elseif (Entity_Index==2)
Vtx2 = [Vtx2; ind, BC_Pt];
elseif (Entity_Index==3)
Vtx3 = [Vtx3; ind, BC_Pt];
elseif (Entity_Index==4)
Vtx4 = [Vtx4; ind, BC_Pt];
else
error('Invalid!');
end
elseif strcmpi(Type,'eval_edge')
if (Entity_Index==1)
Edge1 = [Edge1; ind, BC_Pt];
elseif (Entity_Index==2)
Edge2 = [Edge2; ind, BC_Pt];
elseif (Entity_Index==3)
Edge3 = [Edge3; ind, BC_Pt];
elseif (Entity_Index==4)
Edge4 = [Edge4; ind, BC_Pt];
elseif (Entity_Index==5)
Edge5 = [Edge5; ind, BC_Pt];
elseif (Entity_Index==6)
Edge6 = [Edge6; ind, BC_Pt];
else
error('Invalid!');
end
elseif strcmpi(Type,'eval_facet')
if (Entity_Index==1)
Face1 = [Face1; ind, BC_Pt];
elseif (Entity_Index==2)
Face2 = [Face2; ind, BC_Pt];
elseif (Entity_Index==3)
Face3 = [Face3; ind, BC_Pt];
elseif (Entity_Index==4)
Face4 = [Face4; ind, BC_Pt];
else
error('Invalid!');
end
elseif strcmpi(Type,'eval_cell')
Tet1 = [Tet1; ind, BC_Pt];
else
error('Invalid!');
end
end
Num_V1 = size(Vtx1,1);
Num_V2 = size(Vtx2,1);
Num_V3 = size(Vtx3,1);
Num_V4 = size(Vtx4,1);
Num_E1 = size(Edge1,1);
Num_E2 = size(Edge2,1);
Num_E3 = size(Edge3,1);
Num_E4 = size(Edge4,1);
Num_E5 = size(Edge5,1);
Num_E6 = size(Edge6,1);
Num_F1 = size(Face1,1);
Num_F2 = size(Face2,1);
Num_F3 = size(Face3,1);
Num_F4 = size(Face4,1);
Num_T1 = size(Tet1,1);
Num_DoF = Num_V1 + Num_V2 + Num_V3 + Num_V4 + ...
Num_E1 + Num_E2 + Num_E3 + Num_E4 + Num_E5 + Num_E6 + ...
Num_F1 + Num_F2 + Num_F3 + Num_F4 + ...
Num_T1;
if (Num_DoF~=length(Nodal_Var))
error('Number of DoFs is incorrect!');
end
CHK_VTX_DOF = max(abs([Num_V1, Num_V2, Num_V3, Num_V4] - Num_V1));
if (CHK_VTX_DOF~=0)
error('Number of Vtx DoFs at each vertex is not the same!');
end
CHK_EDGE_DOF = max(abs([Num_E1, Num_E2, Num_E3, Num_E4, Num_E5, Num_E6] - Num_E1));
if (CHK_EDGE_DOF~=0)
error('Number of Edge DoFs on each edge is not the same!');
end
CHK_FACE_DOF = max(abs([Num_F1, Num_F2, Num_F3, Num_F4] - Num_F1));
if (CHK_FACE_DOF~=0)
error('Number of Face DoFs on each face is not the same!');
end
% setup the vertex DoFs
if ~isempty(Vtx1)
Vtx1 = sortrows(Vtx1,1); % sort based on DoF index
Vtx2 = sortrows(Vtx2,1);
Vtx3 = sortrows(Vtx3,1);
Vtx4 = sortrows(Vtx4,1);
DoFs_on_Vtx = [Vtx1(:,1)'; Vtx2(:,1)'; Vtx3(:,1)'; Vtx4(:,1)'];
else
DoFs_on_Vtx = [];
end
Nodal_Top.V = {DoFs_on_Vtx};
% setup the edge DoFs
if ~isempty(Edge1)
Edge1 = sortrows(Edge1,1); % sort based on DoF index
Edge2 = sortrows(Edge2,1);
Edge3 = sortrows(Edge3,1);
Edge4 = sortrows(Edge4,1);
Edge5 = sortrows(Edge5,1);
Edge6 = sortrows(Edge6,1);
DoFs_on_Edge = [Edge1(:,1)'; Edge2(:,1)'; Edge3(:,1)';
Edge4(:,1)'; Edge5(:,1)'; Edge6(:,1)'];
else
DoFs_on_Edge = [];
end
Nodal_Top.E = {DoFs_on_Edge};
% setup the facet (face) DoFs
if ~isempty(Face1)
Face1 = sortrows(Face1,1); % sort based on DoF index
Face2 = sortrows(Face2,1);
Face3 = sortrows(Face3,1);
Face4 = sortrows(Face4,1);
DoFs_on_Face = [Face1(:,1)'; Face2(:,1)'; Face3(:,1)'; Face4(:,1)'];
else
DoFs_on_Face = [];
end
Nodal_Top.F = {DoFs_on_Face};
% setup the cell (tet) DoFs
if ~isempty(Tet1)
Tet1 = sortrows(Tet1,1); % sort based on DoF index
DoFs_on_Tet = [Tet1(:,1)'];
else
DoFs_on_Tet = [];
end
Nodal_Top.T = {DoFs_on_Tet};
else
error('Not implemented!');
end
Vtx_DoFs = [];
for ii = 1:length(Nodal_Top.V)
Vtx_DoFs = [Vtx_DoFs; Nodal_Top.V{ii}(:)];
end
Edge_DoFs = [];
for ii = 1:length(Nodal_Top.E)
Edge_DoFs = [Edge_DoFs; Nodal_Top.E{ii}(:)];
end
Face_DoFs = [];
for ii = 1:length(Nodal_Top.F)
Face_DoFs = [Face_DoFs; Nodal_Top.F{ii}(:)];
end
Tet_DoFs = [];
for ii = 1:length(Nodal_Top.T)
Tet_DoFs = [Tet_DoFs; Nodal_Top.T{ii}(:)];
end
All_DoFs = [Vtx_DoFs; Edge_DoFs; Face_DoFs; Tet_DoFs];
% final check
Unique_DoFs = unique(All_DoFs);
if (length(All_DoFs)~=length(Unique_DoFs))
error('Not all DoF indices are distinct!');
end
end
|
github
|
eardi/sm-fpca-master
|
Generate_Hcurl_3D_Permuted_Basis_Set.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Elem_Defn/Generators/Generate_Hcurl_3D_Permuted_Basis_Set.m
| 8,790 |
utf_8
|
00356351444fae677df87dce712a3086
|
function Perm_Basis = Generate_Hcurl_3D_Permuted_Basis_Set(Elem,Permute_NV)
%Generate_Hcurl_3D_Permuted_Basis_Set
%
% This generates 24 permutations of the H(curl) basis functions (in 3-D).
% Thr output is an array of structs containing the set of basis functions
% for each permutation. It also contains the corresponding permutation
% signature.
%
% Note: this works with "Premap_Transformation_in_3D.m", in the
% Hcurl_Trans class.
% Copyright (c) 11-02-2016, Shawn W. Walker
% get basis functions on reference element
Ref_Elem = ReferenceFiniteElement(Elem,1);
Quad_NOT_USED = Ref_Elem.Gen_Quadrature_Rule(1, 'tetrahedron'); % bogus! not really used
Eval_Basis = Ref_Elem.Gen_Basis_Function_Evals(Quad_NOT_USED.Pt,1);
clear Ref_Elem;
% define generic affine map (represented by a constant matrix and constant vector)
% the inputs are the vertex coordinates of the corners of the target
% tetrahedron
Generic_Perm_Map = @(X1,X2,X3,X4) {...
[ (X2(1) - X1(1)), (X3(1) - X1(1)), (X4(1) - X1(1));
(X2(2) - X1(2)), (X3(2) - X1(2)), (X4(2) - X1(2));
(X2(3) - X1(3)), (X3(3) - X1(3)), (X4(3) - X1(3))],...
[X1(1); X1(2); X1(3)]};
%
% standard reference tetrahedron vertex coordinates
XC_1 = [0, 0, 0];
XC_2 = [1, 0, 0];
XC_3 = [0, 1, 0];
XC_4 = [0, 0, 1];
Ref_XC = [XC_1; XC_2; XC_3; XC_4];
% max derivative order to compute
%Max_Deriv = Eval_Basis(1).Max_Deriv; % get this!
Num_Basis = length(Eval_Basis);
% need symbolic variables
std_vars = {'x', 'y', 'z'};
tilde_vars = {'x_t', 'y_t', 'z_t'};
syms x y z;
vec_x = [x; y; z];
% rename variables in Eval_Basis (do it once!)
Eval_Basis_Rename = Eval_Basis;
Nodal_BC_Coord = zeros(Num_Basis,4);
for bi = 1:Num_Basis
Eval_Basis_Rename(bi).Base_Func = Eval_Basis_Rename(bi).Base_Func.Rename_Independent_Vars(std_vars,tilde_vars);
% note: we do NOT bother to rename the derivative functions (because they are not used)
Nodal_BC_Coord(bi,:) = Elem.Nodal_Var(bi).Data{1};
end
% loop through all permutations
TEMP_PP = perms([1 2 3 4]);
Perm_List = TEMP_PP(end:-1:1,:);
Num_Perm = size(Perm_List,1);
Perm_Basis(Num_Perm).Signature = [];
Perm_Basis(Num_Perm).Elem = [];
for pp = 1:Num_Perm
% store signature
Perm_Signature = Perm_List(pp,:);
disp(['Current permutation #', num2str(pp), ' / ', num2str(Num_Perm), '. Signature: ', num2str(Perm_Signature)]);
Perm_Tet = get_tetrahedral_entity_permutations(Perm_Signature');
TP = Perm_Signature - 1; % C-style!
Perm_Basis(pp).Signature = TP(1) * 1 +...
TP(2) * 10 +...
TP(3) * 100 +...
TP(4) * 1000;
%
% make the affine map
Perm_Coord = Ref_XC(Perm_Signature,:);
Perm_Map_Data = Generic_Perm_Map(Perm_Coord(1,:),Perm_Coord(2,:),Perm_Coord(3,:),Perm_Coord(4,:));
Sym_Func_Temp = Perm_Map_Data{1} * vec_x + Perm_Map_Data{2};
% need it symbolically (this is my F_{\tilde{T}} map from \hat{T} --> \tilde{T}
Sym_Perm_Map = FELSymFunc(Sym_Func_Temp,std_vars);
% and numerically
Numerical_Perm_Map = @(X) Perm_Map_Data{1} * X + Perm_Map_Data{2} * ones(1,size(X,2));
Jacobian_Matrix = Perm_Map_Data{1};
% build DoF permutation map (from hat{T} to tilde{T})
DoF_Perm = zeros(Num_Basis,1);
% loop through all Topological Entity DoFs
DoF_Perm = Build_DoF_Perm(DoF_Perm,Nodal_BC_Coord,Elem.Nodal_Top.V,Perm_Tet.Vtx,Numerical_Perm_Map);
DoF_Perm = Build_DoF_Perm(DoF_Perm,Nodal_BC_Coord,Elem.Nodal_Top.E,Perm_Tet.Edge,Numerical_Perm_Map);
DoF_Perm = Build_DoF_Perm(DoF_Perm,Nodal_BC_Coord,Elem.Nodal_Top.F,Perm_Tet.Face,Numerical_Perm_Map);
DoF_Perm = Build_DoF_Perm(DoF_Perm,Nodal_BC_Coord,Elem.Nodal_Top.T,Perm_Tet.Tet,Numerical_Perm_Map);
% error check
if (length(unique(DoF_Perm))~=Num_Basis)
error('DoF_Perm is not formed properly!');
end
if (min(DoF_Perm)==0)
error('One of the DoFs was not found!');
end
% init basis set
New_Basis = Elem.Basis;
% loop through basis set
for bi = 1:Num_Basis
% get function on \tilde{T}
Perm_bi = DoF_Perm(bi);
Single_Basis_Func = Eval_Basis_Rename(Perm_bi).Base_Func; % a FELSymFunc
% compute effective function on \hat{T}
Mapped_Basis_Func = Single_Basis_Func.Compose_Function(Sym_Perm_Map);
% multiply by jacobian transpose
Single_Basis_Func_hat = Mapped_Basis_Func; % init
Single_Basis_Func_hat.Func = Jacobian_Matrix' * Mapped_Basis_Func.Func; % a "sym"
% BEGIN: TEST CODE
% create FELSymBasisCalc object
BF_hat = FELSymBasisCalc(Single_Basis_Func_hat,1);
BF_hat_d_dx = BF_hat.Get_Derivative([1 0 0]);
BF_hat_d_dy = BF_hat.Get_Derivative([0 1 0]);
BF_hat_d_dz = BF_hat.Get_Derivative([0 0 1]);
BF_hat_grad = [BF_hat_d_dx.Func, BF_hat_d_dy.Func, BF_hat_d_dz.Func];
BF_d_dx = Eval_Basis(Perm_bi).Get_Derivative([1 0 0]);
BF_d_dy = Eval_Basis(Perm_bi).Get_Derivative([0 1 0]);
BF_d_dz = Eval_Basis(Perm_bi).Get_Derivative([0 0 1]);
BF_d_dx = BF_d_dx.Rename_Independent_Vars(std_vars,tilde_vars);
BF_d_dy = BF_d_dy.Rename_Independent_Vars(std_vars,tilde_vars);
BF_d_dz = BF_d_dz.Rename_Independent_Vars(std_vars,tilde_vars);
BF_d_dx = BF_d_dx.Compose_Function(Sym_Perm_Map);
BF_d_dy = BF_d_dy.Compose_Function(Sym_Perm_Map);
BF_d_dz = BF_d_dz.Compose_Function(Sym_Perm_Map);
BF_grad = [BF_d_dx.Func, BF_d_dy.Func, BF_d_dz.Func];
BF_grad_transform = Jacobian_Matrix' * BF_grad * Jacobian_Matrix;
CHK1 = simplify(BF_hat_grad - BF_grad_transform);
if (sum(abs(CHK1(:)))~=sym(0))
error('Something does not match!');
end
% END: TEST CODE
% store the basis function (defined on \hat{T}) as a string
New_Basis(bi).Func = {char(Single_Basis_Func_hat.Func(1));
char(Single_Basis_Func_hat.Func(2));
char(Single_Basis_Func_hat.Func(3))};
end
% store the permuted basis!
Perm_Basis(pp).Elem = Elem; % init
Perm_Basis(pp).Elem.Basis = New_Basis;
Perm_Basis(pp).Elem.Nodal_Var = Permute_NV(DoF_Perm,Perm_Tet,Sym_Perm_Map,Jacobian_Matrix);
end
end
function DoF_Perm = Build_DoF_Perm(DoF_Perm,Nodal_BC_Coord,...
Topological_DoFs,Perm_Entity,Numerical_Perm_Map)
%
% DoF_Perm : \hat{T} --> \tilde{T}
% note: the master DoFs (and master finite element) are defined on \tilde{T}
% loop through all DoFs of given topology
for si = 1:length(Topological_DoFs)
DoF_Set = Topological_DoFs{si};
for entity_hat = 1:size(DoF_Set,1)
% get corresponding entity in \tilde{T}
entity_tilde = Perm_Entity(entity_hat);
% get topological entity DoFs (on \tilde{T})
DoF_Indices_tilde = DoF_Set(entity_tilde,:);
% get the corresponding DoF indices on \hat{T}
% note: the DoF indices are arranged the same way on \hat{T}
DoF_Indices_hat = DoF_Set(entity_hat,:);
% get barycentric coordinates of DoFs
BC_hat = Nodal_BC_Coord(DoF_Indices_hat,:);
BC_tilde = Nodal_BC_Coord(DoF_Indices_tilde,:);
% make sure to get where the "hat" coordinates get mapped to
Ref_Coord_hat = BC_hat(:,2:end);
Mapped_Ref_Pt = Numerical_Perm_Map(Ref_Coord_hat')';
Mapped_BC_hat = [1 - sum(Mapped_Ref_Pt,2), Mapped_Ref_Pt];
% deduce mapping from the coordinates
Map_hat_to_tilde = Get_Mapping_via_Coordinates(Mapped_BC_hat,BC_tilde);
DoF_Perm(DoF_Indices_hat) = DoF_Indices_tilde(Map_hat_to_tilde);
end
end
end
function Map_hat_to_tilde = Get_Mapping_via_Coordinates(BC_hat,BC_tilde)
Num_Coord = size(BC_hat,1);
Map_hat_to_tilde = zeros(Num_Coord,1); % init
Indices = (1:1:Num_Coord)';
for ii_hat = 1:Num_Coord
Current_BC_hat = BC_hat(ii_hat,:);
Diff_1 = BC_tilde - [Current_BC_hat(1)*ones(Num_Coord,1), Current_BC_hat(2)*ones(Num_Coord,1),...
Current_BC_hat(3)*ones(Num_Coord,1), Current_BC_hat(4)*ones(Num_Coord,1)];
Diff_CHK = max(abs(Diff_1),[],2);
Zero_Mask = (Diff_CHK < 1e-15);
if (sum(Zero_Mask)~=1)
error('Either no DoF was found, or too many!');
end
% record correspondance
Map_hat_to_tilde(ii_hat) = Indices(Zero_Mask);
end
end
|
github
|
eardi/sm-fpca-master
|
Get_Nedelec_1stKind_On_Simplex.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Elem_Defn/Generators/Get_Nedelec_1stKind_On_Simplex.m
| 12,379 |
utf_8
|
474b711c270f1fc0b8f9006820326e70
|
function [Nodal_Basis, Nodal_Var] = Get_Nedelec_1stKind_On_Simplex(dim,deg_k,use_std)
%Get_Nedelec_1stKind_On_Simplex
%
% This computes the Nedelec (1st kind) basis functions on a simplex.
%
% This uses the Paul Wesson trick for choosing tangent basis vectors (for
% edges and faces); i.e. the global numbering of the element vertices
% dictates the choice of tangent vectors (see
% "Generate_Nedelec_1stKind_Element_File" for more info).
%
% The last input (only used in 3-D) determines which reference finite
% element to get. Let the global vertices of the physical mesh element
% (tetrahedron) be given by [V1, V2, V3, V4]
%
% use_std = true: this assumes that the vertex indices satisfy:
% V1 < V2 < V3 < V4 (standard ascending ordering).
% This dictates a particular choice of tangent basis vectors.
%
% use_std = false: this assumes that the vertex indices satisfy:
% V1 < V3 < V2 < V4 (reflect element; mirror image).
% This dictates a different choice of tangent basis vectors.
%
% Note: if the physical element does not satisfy either of these, then
% you need another reference element!
% Copyright (c) 11-07-2016, Shawn W. Walker
% set default
if (nargin==2)
use_std = true;
end
if isempty(use_std)
use_std = true;
end
disp(['Solve for Nedelec (1st kind) degree ', num2str(deg_k), ' basis functions (on ', num2str(dim), '-D reference simplex):']);
if (deg_k < 1)
% invalid degree, so return *nothing*
Nodal_Basis = [];
Nodal_Var = [];
return;
end
% get parameterizations of the reference simplex
if (dim==1)
% get params of the reference interval
%Cell = interval_parameterizations();
error('Invalid!');
elseif (dim==2)
% get params of the reference triangle
Cell = triangle_parameterizations();
elseif (dim==3)
% get params of the reference tetrahedron
Cell = tetrahedron_parameterizations();
else
error('Dimension not implemented!');
end
indep_vars = Cell.Param_Inv; % col. vector list of independent variables
% define a set of basis functions (indep. variables are x,y)
num_comp = dim;
Basis_1 = basis_vector_polys_deg_k(indep_vars,deg_k-1,num_comp);
% get the special polynomial space S_k
Basis_2 = basis_vector_polys_deg_k_Sk(indep_vars,deg_k);
Basis = [Basis_1, Basis_2]; % direct sum!
% for ii = 1:length(Basis)
% Basis(ii).func
% end
% error check
if (dim==2)
Num_Basis = deg_k*(deg_k + 2);
elseif (dim==3)
Num_Basis = round((1/2)* deg_k *(deg_k + 2)*(deg_k + 3));
elseif (dim < 2)
error('Invalid dimension!');
else
error('Dimension not implemented!');
end
if (Num_Basis~=length(Basis))
error('Number of basis functions is invalid!');
end
indep_vars_cell = num2cell(indep_vars);
if (dim==2)
% get Lagrange nodal basis functions on reference edge
% (i.e. the unit interval)
[Lagrange_Basis_Edge, Lagrange_Nodal_Pt_Edge] = Get_Lagrange_On_Simplex(dim-1,deg_k-1);
Local_Edge_Var = num2cell(Cell.Edge(1).Local_Var);
% replace x with u
Lagrange_Basis_Edge = change_basis_func_independent_variable(Lagrange_Basis_Edge,indep_vars_cell(1:dim-1),Local_Edge_Var);
% get Lagrange nodal basis functions on unit cell (triangle)
[Lagrange_Basis_Cell, Lagrange_Nodal_Pt_Cell] = Get_Lagrange_On_Simplex(dim,deg_k-2);
% don't need to change variables
elseif (dim==3)
% get Lagrange nodal basis functions on reference edge
% (i.e. the unit interval)
[Lagrange_Basis_Edge, Lagrange_Nodal_Pt_Edge] = Get_Lagrange_On_Simplex(dim-2,deg_k-1);
Local_Edge_Var = num2cell(Cell.Edge(1).Local_Var);
% replace x with u
Lagrange_Basis_Edge = change_basis_func_independent_variable(Lagrange_Basis_Edge,indep_vars_cell(1:dim-2),Local_Edge_Var);
% get Lagrange nodal basis functions on reference facet
% (i.e. the unit triangle)
[Lagrange_Basis_Facet, Lagrange_Nodal_Pt_Facet] = Get_Lagrange_On_Simplex(dim-1,deg_k-2);
Local_Facet_Var = num2cell(Cell.Facet(1).Local_Var);
% replace {x,y} with {u,v}
Lagrange_Basis_Facet = change_basis_func_independent_variable(Lagrange_Basis_Facet,indep_vars_cell(1:dim-1),Local_Facet_Var);
% get Lagrange nodal basis functions on unit cell (tetrahedron)
[Lagrange_Basis_Cell, Lagrange_Nodal_Pt_Cell] = Get_Lagrange_On_Simplex(dim,deg_k-3);
% don't need to change variables
elseif (dim==1)
error('Invalid dimension!');
else
error('Not implemented!');
end
% BEGIN: define nodal variable data (in order of the DoF index)
% these effectively specify what the Degrees-of-Freedom (DoFs) are
% Note: these involve integral averages
Num_Nodal_Var = Num_Basis;
Nodal_Var(Num_Nodal_Var).Data = [];
nodal_index = 0; % init
% loop through edge averages
if (dim==2)
Num_Edge = 3;
elseif (dim==3)
Num_Edge = 6;
else
error('Invalid!');
end
for ei = 1:Num_Edge
% get the correct orientation (for H(curl)!) of the unit tangent vector of the edge
Tangent_Vector = get_edge_tangent_vector_for_Hcurl(Cell,dim,ei,use_std);
for li = 1:length(Lagrange_Basis_Edge)
local_bf = Lagrange_Basis_Edge(li).Func; % local Lagrange basis function
% map that function to the edge
Xmap_Inv = Cell.Edge(ei).Param_Inv;
local_bf = subs(local_bf,Local_Edge_Var,Xmap_Inv);
% store the corresponding nodal (Lagrange) point coordinates
NP = Lagrange_Nodal_Pt_Edge(li).Data{1};
% map to the facet in question
Xmap = Cell.Edge(ei).Param;
Mapped_Nodal_Point = subs(Xmap,Local_Edge_Var,NP);
% append nodal data
nodal_index = nodal_index + 1;
Nodal_Var(nodal_index).Data = {Mapped_Nodal_Point, local_bf*Tangent_Vector, 'int_edge', ei};
end
end
% loop through facet averages
if (dim==3)
for ti = 1:dim-1 % loop through the different tangent vectors in each facet
Num_Facet = 4;
for fi = 1:Num_Facet
Tangent = get_facet_tangent_vectors_for_Hcurl(Cell,fi,use_std);
for li = 1:length(Lagrange_Basis_Facet)
local_bf = Lagrange_Basis_Facet(li).Func; % local Lagrange basis function
% map that function to the facet
Xmap_Inv = Cell.Facet(fi).Param_Inv;
local_bf = subs(local_bf,Local_Facet_Var,Xmap_Inv);
% store the corresponding nodal (Lagrange) point coordinates
NP = Lagrange_Nodal_Pt_Facet(li).Data{1};
% map to the facet in question
Xmap = Cell.Facet(fi).Param;
Mapped_Nodal_Point = subs(Xmap,Local_Facet_Var,NP);
% append nodal data
nodal_index = nodal_index + 1;
Nodal_Var(nodal_index).Data = {Mapped_Nodal_Point, local_bf*Tangent(ti).Vector, 'int_facet', fi, 'dof_set', ti};
end
end
end
end
% loop through cell averages
for vi = 1:dim % loop through vector components
Vector = zeros(dim,1);
Vector(vi) = 1;
for li = 1:length(Lagrange_Basis_Cell)
local_bf = Lagrange_Basis_Cell(li).Func; % local Lagrange basis function
% already mapped to the cell
% store the nodal (Lagrange) points
Nodal_Point = Lagrange_Nodal_Pt_Cell(li).Data{1}; % already mapped
% append nodal data
nodal_index = nodal_index + 1;
Nodal_Var(nodal_index).Data = {Nodal_Point, local_bf*Vector, 'int_cell', 1, 'dof_set', vi};
end
end
% END: define nodal variable data (in order of the DoF index)
% generate matrix entries
N = length(Nodal_Var);
if (N~=Num_Nodal_Var) % error check
error('Number of nodal variables is too high!');
end
% init Vandermonde matrix
A = sym(zeros(N,N));
% fill in the "Vandermonde" matrix
disp('Fill Vandermonde matrix A:');
for ii=1:N
% get the current nodal variable (DoF)
Nodal_Var_Data = Nodal_Var(ii).Data;
Eval_Nodal_Variable = Nedelec_1stKind_On_Simplex_Nodal_Variable(Cell,Nodal_Var_Data,indep_vars);
% loop through all of the (primal) basis functions
for jj=1:N
vphi = Basis(jj).func; % get basis function
% insert into matrix
A(ii,jj) = Eval_Nodal_Variable(vphi); % eval nodal variable
end
disp(['Compute A(', num2str(ii), ', 1:', num2str(N), ').']);
end
disp('Finished forming Vandermonde matrix...');
% lambda = abs(eig(double(A)));
% COND = max(lambda) / min(lambda);
% COND
% solve for coefficients
EYE_SYM = sym(eye(N));
disp('Solve for coefficients:');
COEF = A \ EYE_SYM;
% compute the nodal basis functions
Nodal_Basis(N).Func = [];
for ind=1:N
TEMP = 0; % reset!
for jj=1:N
TEMP = TEMP + COEF(jj,ind) * Basis(jj).func;
end
Nodal_Basis(ind).Func = simplify(TEMP);
end
% display
for ind=1:N
disp(['Nodal Basis Function #', num2str(ind), ':']);
pretty(Nodal_Basis(ind).Func)
end
end
function tau = get_edge_tangent_vector_for_Hcurl(Cell,dim,edge_index,use_std)
% this returns a tangent vector so that it points from a vertex of lower
% index **toward a vertex of higher index**. This is the Paul Wesson trick.
% NOTE: these tangent vectors are *unit* tangent vectors. This is how the
% degrees-of-freedom are defined.
tau = Cell.Edge(edge_index).Tangent;
% adjust sign if necessary
if (use_std)
if (dim==2)
if (edge_index==2)
% flip this one relative to the "standard" assumed orientation
tau = -tau;
end
elseif (dim==3)
% V1 < V2 < V3 < V4
if (edge_index==6)
% flip this one relative to the "standard" assumed orientation
tau = -tau;
end
else
error('Invalid or not implemented!');
end
else
% this only happens in 3-D
if (dim==3)
% V1 < V3 < V2 < V4
if or(edge_index==4,edge_index==6)
% flip this relative to the "standard" assumed orientation
tau = -tau;
end
else
error('Invalid or not implemented!');
end
end
end
function tau = get_facet_tangent_vectors_for_Hcurl(Cell,face_index,use_std)
% this returns two tangent vectors (on the given facet in 3-D) that satisfy
% the Paul Wesson trick. I.e. for the given face, with vertices [a,b,c]
% given in ascending order with respect to the local vertex index, the
% tangent vectors are given by: tau_1 = b - a, tau_2 = c - a.
% WARNING!!! these are not necessarily *unit* tangent vectors.
% They come from taking the difference of the corner vertex coordinates.
% Hence, the tangents on the boundary of the "111" face (i.e. face #1) are
% length sqrt(2).
% Note: this is how the degrees-of-freedom are defined.
tau(2).Vector = []; % init
if (use_std)
% V1 < V2 < V3 < V4
if (face_index==1)
tau(1).Vector = Cell.Edge(4).Tangent * Cell.Edge(4).Measure; % e4
tau(2).Vector = -Cell.Edge(6).Tangent * Cell.Edge(6).Measure; % -e6
elseif (face_index==2)
tau(1).Vector = Cell.Edge(2).Tangent; % e2
tau(2).Vector = Cell.Edge(3).Tangent; % e3
elseif (face_index==3)
tau(1).Vector = Cell.Edge(1).Tangent; % e1
tau(2).Vector = Cell.Edge(3).Tangent; % e3
elseif (face_index==4)
tau(1).Vector = Cell.Edge(1).Tangent; % e1
tau(2).Vector = Cell.Edge(2).Tangent; % e2
else
error('Invalid!');
end
else % mirror image
% V1 < V3 < V2 < V4
if (face_index==1)
tau(1).Vector = -Cell.Edge(4).Tangent * Cell.Edge(4).Measure; % -e4
tau(2).Vector = Cell.Edge(5).Tangent * Cell.Edge(5).Measure; % e5
elseif (face_index==2)
tau(1).Vector = Cell.Edge(2).Tangent; % e2
tau(2).Vector = Cell.Edge(3).Tangent; % e3
elseif (face_index==3)
tau(1).Vector = Cell.Edge(1).Tangent; % e1
tau(2).Vector = Cell.Edge(3).Tangent; % e3
elseif (face_index==4)
tau(1).Vector = Cell.Edge(2).Tangent; % e2
tau(2).Vector = Cell.Edge(1).Tangent; % e1
else
error('Invalid!');
end
end
end
|
github
|
eardi/sm-fpca-master
|
Generate_Nedelec_1stKind_Element_File.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Elem_Defn/Generators/Generate_Nedelec_1stKind_Element_File.m
| 22,662 |
utf_8
|
379f28827fcd07fe385a815545b5b676
|
function status = Generate_Nedelec_1stKind_Element_File(Element_Domain,Degree_k,Output_Dir,Use_Std)
%Generate_Nedelec_1stKind_Element_File
%
% This generates a finite element reference m-file that defines a
% particular Nedelec (1st-kind) element of given fixed degree on a given
% reference domain.
%
% The inputs are:
% Element_Domain = 'interval', 'triangle', 'tetrahedron', etc.
% Degree_k = polynomial degree of finite element.
% Output_FileName = string specifying where to write the file.
% Use_Std = bool only used in 3-D. Indicates the ordering of
% the global vertices of the tetrahedral element,
% which is defined by [V1, V2, V3, V4]
% true: V1 < V2 < V3 < V4 (ascending order)
% false: V1 < V3 < V2 < V4 (reflect mirror element).
% Copyright (c) 11-07-2016, Shawn W. Walker
% set default
if (nargin==3)
Use_Std = true;
end
if isempty(Use_Std)
Use_Std = true;
end
% get basic info text
[Element_Domain, Domain_STR, Domain_Fig_ASCII, Dim] = setup_generic_element_file_text(Element_Domain);
ENDL = '\n';
TAB = ' ';
%TAB2 = [TAB, TAB];
%TAB3 = [TAB2, TAB];
%TAB4 = [TAB3, TAB];
% get the (reference) finite element space
if strcmpi(Element_Domain,'interval')
error('Invalid domain!');
elseif strcmpi(Element_Domain,'triangle')
[Nodal_Basis, Nodal_Var] = Get_Nedelec_1stKind_On_Simplex(Dim,Degree_k,Use_Std);
elseif strcmpi(Element_Domain,'tetrahedron')
[Nodal_Basis, Nodal_Var] = Get_Nedelec_1stKind_On_Simplex(Dim,Degree_k,Use_Std);
else
error('Not implemented!');
end
% setup filename
Degree_str = num2str(Degree_k);
Dim_str = num2str(Dim);
FuncName = ['nedelec_1stkind_deg', Degree_str, '_dim', Dim_str];
if (~Use_Std)
% save mirror image element
FuncName = [FuncName, '_mirror_image'];
end
Output_FileName = fullfile(Output_Dir, [FuncName, '.m']);
% open file for writing
fid = fopen(Output_FileName, 'w');
% define write line function
write_line = @(STR) fprintf(fid, [STR, ENDL]);
write_string = @(STR) fprintf(fid, STR);
% write header
write_line(['', 'function Elem = ', FuncName, '(Type_STR)']);
write_line(['%%', FuncName]);
write_line(['%%']);
write_line(['%%', TAB, 'This defines a reference finite element to be used by FELICITY.']);
write_line(['%%', TAB, 'INPUT: string = ''CG''/''DG'' (continuous/DIScontinuous galerkin).']);
write_line(['%%']);
write_line(['%%', TAB, 'Nedelec (1st-kind) H(curl) Finite Element of degree = ', Degree_str, ', in dimension = ', Dim_str, '.']);
write_line(['%%']);
if strcmpi(Element_Domain,'tetrahedron')
% only applicable in 3-D
write_line(['%%', TAB, 'This assumes the tetrahedral element [V_1, V_2, V_3, V_4] satisfies:']);
if Use_Std
write_line(['%%', TAB, 'V_1 < V_2 < V_3 < V_4 (ascending order)']);
else
write_line(['%%', TAB, 'V_1 < V_3 < V_2 < V_4 (mirror image the ascending order case)']);
end
write_line(['%%', TAB, '(see below for more information.)']);
end
write_line(['%%']);
write_line(['%%', TAB, 'Reference Domain: ', Domain_STR, '.']);
write_line(['%%']);
write_string([Domain_Fig_ASCII]);
write_line(['%%']);
write_line(['%%', TAB, 'The basis functions are vector-valued (number of components = topological dimension).']);
write_line(['%%']);
write_line(['%%', TAB, 'The basis functions associated with Degrees-of-Freedom (DoFs) on an edge']);
write_line(['%%', TAB, 'have an orientation dictated by the edge''s orientation.']);
write_line(['%%', TAB, 'The orientation of an edge is defined to point from the vertex of']);
write_line(['%%', TAB, 'lower index toward the vertex of higher index. In other words, given an']);
write_line(['%%', TAB, 'edge [V_i, V_j], where i < j, the tangent vector points from V_i toward V_j.']);
write_line(['%%']);
write_line(['%%', TAB, 'The basis functions associated with Degrees-of-Freedom (DoFs) on a facet (in 3-D)']);
write_line(['%%', TAB, 'have an orientation dictated by the tangent vectors of the facet.']);
write_line(['%%', TAB, 'In this case, we use the Paul Wesson trick. Given a facet, we order its']);
write_line(['%%', TAB, 'vertices [V_i, V_j, V_k] so that i < j < k. Then the tangent vectors are:']);
write_line(['%%', TAB, 'tangent_1 = V_j - V_i, tangent_2 = V_k - V_i.']);
write_line(['%%']);
write_line(['%%', TAB, 'For simplicity, the basis functions specified in this file assume the']);
if strcmpi(Element_Domain,'triangle')
write_line(['%%', TAB, 'global vertices of the 2-D element [V_1, V_2, V_3] are ordered as:']);
write_line(['%%', TAB, 'V1 < V2 < V3 (ascending order)']);
write_line(['%%']);
write_line(['%%', TAB, 'Thus, one needs to introduce sign changes of the basis functions when mapping to']);
write_line(['%%', TAB, 'the *actual* element in the mesh. This is because the actual element will']);
write_line(['%%', TAB, 'not (in general) have its vertices ordered in ascending index order.']);
write_line(['%%', TAB, 'Note: a different ordering induces a sign change of the edge tangent vectors,']);
write_line(['%%', TAB, 'so you only need to flip signs of associated basis functions.']);
write_line(['%%']);
write_line(['%%', TAB, 'FELICITY handles these sign changes automatically when assembling matrices,']);
write_line(['%%', TAB, 'evaluating interpolations, etc. So you do not have to "worry" about it,']);
write_line(['%%', TAB, 'but you should *know* about it.']);
elseif strcmpi(Element_Domain,'tetrahedron')
write_line(['%%', TAB, 'global vertices of the 3-D element [V_1, V_2, V_3, V_4] are ordered as:']);
if Use_Std
write_line(['%%', TAB, 'V1 < V2 < V3 < V4 (ascending order)']);
else
write_line(['%%', TAB, 'V1 < V3 < V2 < V4 (mirror image the ascending order case)']);
end
write_line(['%%']);
write_line(['%%', TAB, 'Thus, one needs to ensure that the *actual* element vertices are ordered this']);
write_line(['%%', TAB, 'way when mapping the basis functions. If the actual element does not have this']);
write_line(['%%', TAB, 'ordering, then you need to use a different set of basis functions! For example,']);
write_line(['%%', TAB, 'if the actual element vertices are defined as [a_i, a_j, a_k, a_l], but the']);
write_line(['%%', TAB, 'ordering is i < k < l < j, then you must use the correct set of basis functions']);
write_line(['%%', TAB, 'for that ordering (*not* this file!).']);
write_line(['%%']);
write_line(['%%', TAB, 'FELICITY stores two sets of basis functions: one for each of these orderings:']);
write_line(['%%', TAB, 'V1 < V2 < V3 < V4 (ascending order)']);
write_line(['%%', TAB, 'V1 < V3 < V2 < V4 (mirror image the ascending order case)']);
write_line(['%%', TAB, 'Therefore, make sure that your 3-D triangulations contain only these orderings;']);
write_line(['%%', TAB, 'otherwise, you get an **error** message.']);
write_line(['%%', TAB, 'Note: there is a MeshTetrahedron method to set this ordering, with all mesh']);
write_line(['%%', TAB, ' elements having positive volume.']);
write_line(['%%']);
write_line(['%%', TAB, 'FELICITY''s code generation automatically handles this, so you do not need to']);
write_line(['%%', TAB, '"worry" about it, but you should *know* about it.']);
write_line(['%%', TAB, 'Note: if a mesh element does not satisfy either ordering, then you will get']);
write_line(['%%', TAB, ' an error message when you assemble matrices or evaluate interpolations.']);
else
error('Not implemented!');
end
write_line(['']);
current_date = date;
write_line(['%%', ' Copyright (c) ', current_date, ', Shawn W. Walker']);
write_line(['']);
write_line(['%% name it!']);
write_line(['Elem.Name = mfilename;']);
write_line(['']);
write_line(['%% determine continuous or discontinuous galerkin space']);
write_line(['if (nargin==0)']);
write_line([TAB, 'Type_STR = ''CG''; %% default']);
write_line(['end']);
write_line(['if strcmpi(Type_STR,''cg'')']);
write_line([TAB, 'Elem.Type = ''CG'';']);
write_line(['elseif strcmpi(Type_STR,''dg'')']);
write_line([TAB, 'Elem.Type = ''DG'';']);
write_line(['else']);
write_line([TAB, 'error(''Invalid input type! Must be ''''CG'''' or ''''DG''''.'');']);
write_line(['end']);
write_line(['']);
write_line(['%% topological dimension and domain']);
write_line(['Elem.Dim = ', Dim_str, ';']);
write_line(['Elem.Domain = ''', Element_Domain, ''';']);
write_line(['']);
write_line(['%% nodal basis function definitions (in the order of their local Degree-of-Freedom index)']);
Num_Basis = length(Nodal_Basis);
write_line(['Elem.Basis(', num2str(Num_Basis), ').Func = []; %% init']);
% loop through nodal basis
for ii = 1:length(Nodal_Basis)
BF = Nodal_Basis(ii).Func;
Basis_Func_Str = write_element_file_basis_func_string(BF);
write_line(['Elem.Basis(', num2str(ii), ').Func = {', Basis_Func_Str, '};']);
end
write_line(['%% local mapping transformation to use']);
Transformation_Type_str = 'Hcurl_Trans';
write_line(['Elem.Transformation = ''', Transformation_Type_str, ''';']);
write_line(['Elem.Degree = ', Degree_str, ';']);
write_line(['']);
write_line(['%% nodal variable data (in the order of their local Degree-of-Freedom index)']);
write_line(['%% (the nodal point is given in barycentric coordinates)']);
Num_Nodal_Var = length(Nodal_Var);
write_line(['Elem.Nodal_Var(', num2str(Num_Nodal_Var), ').Data = []; %% init']);
% loop through nodal variables
for ii = 1:length(Nodal_Var)
NV = Nodal_Var(ii).Data;
Nodal_BC_str = write_element_file_barycentric_string(NV{1});
% generate string for (vector-valued) dual basis function
BF = NV{2};
if (Dim==2)
DB_1 = char(BF(1));
DB_2 = char(BF(2));
Dual_Basis_str = ['[', DB_1, '; ', DB_2, ']'];
elseif (Dim==3)
DB_1 = char(BF(1));
DB_2 = char(BF(2));
DB_3 = char(BF(3));
Dual_Basis_str = ['[', DB_1, '; ', DB_2, '; ', DB_3, ']'];
elseif (Dim==1)
error('Invalid!');
else
error('Not implemented!');
end
% write Nedelec element nodal variable data string
if strcmpi(NV{3},'int_edge')
Nodal_Var_Data_str = ['{', Nodal_BC_str, ', ''', Dual_Basis_str, ''', ''', NV{3}, ''', ', num2str(NV{4}), '}'];
elseif or(strcmpi(NV{3},'int_facet'),strcmpi(NV{3},'int_cell'))
Nodal_Var_Data_str = ['{', Nodal_BC_str, ', ''', Dual_Basis_str, ''', ''', NV{3}, ''', ',...
num2str(NV{4}), ', ''', NV{5}, ''', ', num2str(NV{6}), '}'];
else
error('Invalid!');
end
write_line(['Elem.Nodal_Var(', num2str(ii), ').Data = ', Nodal_Var_Data_str, ';']);
end
write_line(['']);
write_line(['%%%%%%%%%% topological arrangement of nodal points %%%%%%%%%%']);
write_line(['%% note: multiple sets of nodal variables can be associated with each topological entity.']);
write_line(['%% This is done by defining multiple matrix arrays within each matlab cell.']);
write_line(['%% See the FELICITY manual for more info.']);
write_line(['']);
Nodal_Top = get_nodal_top_arrangement(Element_Domain,Nodal_Var);
DoF_TAB = ' ';
write_line(['%% nodes attached to vertices']);
if ~isempty(Nodal_Top.V{1})
write_line(['Elem.Nodal_Top.V = {...']);
Nodal_Sets_str = write_element_file_nodal_top_string(Nodal_Top.V,DoF_TAB);
write_line(Nodal_Sets_str);
write_line([DoF_TAB, '};']);
write_line(['%%']);
else
write_line(['Elem.Nodal_Top.V = {[]};']);
end
write_line(['']);
write_line(['%% nodes attached to edges']);
if ~isempty(Nodal_Top.E{1})
write_line(['Elem.Nodal_Top.E = {...']);
Nodal_Sets_str = write_element_file_nodal_top_string(Nodal_Top.E,DoF_TAB);
write_line(Nodal_Sets_str);
write_line([DoF_TAB, '};']);
write_line(['%%']);
else
write_line(['Elem.Nodal_Top.E = {[]};']);
end
write_line(['']);
write_line(['%% nodes attached to triangles (faces)']);
if ~isempty(Nodal_Top.F{1})
write_line(['Elem.Nodal_Top.F = {...']);
Nodal_Sets_str = write_element_file_nodal_top_string(Nodal_Top.F,DoF_TAB);
write_line(Nodal_Sets_str);
write_line([DoF_TAB, '};']);
write_line(['%%']);
else
write_line(['Elem.Nodal_Top.F = {[]};']);
end
write_line(['']);
write_line(['%% nodes attached to tetrahedra (cells)']);
if ~isempty(Nodal_Top.T{1})
write_line(['Elem.Nodal_Top.T = {...']);
Nodal_Sets_str = write_element_file_nodal_top_string(Nodal_Top.T,DoF_TAB);
write_line(Nodal_Sets_str);
write_line([DoF_TAB, '};']);
write_line(['%%']);
else
write_line(['Elem.Nodal_Top.T = {[]};']);
end
write_line(['']);
write_string(['end']);
% DONE!
status = fclose(fid);
end
function Nodal_Top = get_nodal_top_arrangement(Element_Domain,Nodal_Var)
%
% This arranges the nodal variables (i.e. the nodal points) on their
% corresponding topological entities.
if or(strcmpi(Element_Domain,'interval'),isempty(Nodal_Var))
% this is invalid!
Nodal_Top.V = {[]};
Nodal_Top.E = {[]};
Nodal_Top.F = {[]};
Nodal_Top.T = {[]};
elseif strcmpi(Element_Domain,'triangle')
% init
Edge1 = [];
Edge2 = [];
Edge3 = [];
Cell_1 = [];
Cell_2 = [];
for ind = 1:length(Nodal_Var)
NV = Nodal_Var(ind).Data;
Pt = NV{1};
BC_Pt = double(convert_to_barycentric(Pt))';
Type = NV{3};
Entity_Index = NV{4};
if strcmpi(Type,'int_edge')
if (Entity_Index==1)
Edge1 = [Edge1; ind, BC_Pt];
elseif (Entity_Index==2)
Edge2 = [Edge2; ind, BC_Pt];
elseif (Entity_Index==3)
Edge3 = [Edge3; ind, BC_Pt];
else
error('Invalid!');
end
elseif strcmpi(Type,'int_cell')
dof_set = NV{6};
if (dof_set==1)
Cell_1 = [Cell_1; ind, BC_Pt];
elseif (dof_set==2)
Cell_2 = [Cell_2; ind, BC_Pt];
else
error('Invalid!');
end
else
error('Invalid!');
end
end
Num_E1 = size(Edge1,1);
Num_E2 = size(Edge2,1);
Num_E3 = size(Edge3,1);
Num_C_1 = size(Cell_1,1);
Num_C_2 = size(Cell_2,1);
Num_DoF = Num_E1 + Num_E2 + Num_E3 + Num_C_1 + Num_C_2;
if (Num_DoF~=length(Nodal_Var))
error('Number of DoFs is incorrect!');
end
CHK_EDGE_DOF = max(abs([Num_E1, Num_E2, Num_E3] - Num_E1));
if (CHK_EDGE_DOF~=0)
error('Number of Edge DoFs on each edge is not the same!');
end
if (Num_C_1~=Num_C_2)
error('Number of Cell DoFs in each set is not the same!');
end
% there are no vertex DoFs
Nodal_Top.V = {[]};
% setup the edge DoFs
Edge1 = sortrows(Edge1,1); % sort based on DoF index
Edge2 = sortrows(Edge2,1);
Edge3 = sortrows(Edge3,1);
DoFs_on_Edge = [Edge1(:,1)'; Edge2(:,1)'; Edge3(:,1)'];
Nodal_Top.E = {DoFs_on_Edge};
% setup the cell (face) DoFs
if ~isempty(Cell_1)
Cell_1 = sortrows(Cell_1,1); % sort based on DoF index
Cell_2 = sortrows(Cell_2,1);
DoFs_on_Face_1 = [Cell_1(:,1)'];
DoFs_on_Face_2 = [Cell_2(:,1)'];
% there are 2 sets of DoFs (one for each vector component)
Nodal_Top.F = {DoFs_on_Face_1, DoFs_on_Face_2};
else
Nodal_Top.F = {[]};
end
% there are no other DoFs
Nodal_Top.T = {[]};
elseif strcmpi(Element_Domain,'tetrahedron')
% init
Edge1 = [];
Edge2 = [];
Edge3 = [];
Edge4 = [];
Edge5 = [];
Edge6 = [];
Face1_1 = []; % dof_set #1
Face2_1 = [];
Face3_1 = [];
Face4_1 = [];
Face1_2 = []; % dof_set #2
Face2_2 = [];
Face3_2 = [];
Face4_2 = [];
Cell_1 = [];
Cell_2 = [];
Cell_3 = [];
for ind = 1:length(Nodal_Var)
NV = Nodal_Var(ind).Data;
Pt = NV{1};
BC_Pt = double(convert_to_barycentric(Pt))';
Type = NV{3};
Entity_Index = NV{4};
if strcmpi(Type,'int_edge')
if (Entity_Index==1)
Edge1 = [Edge1; ind, BC_Pt];
elseif (Entity_Index==2)
Edge2 = [Edge2; ind, BC_Pt];
elseif (Entity_Index==3)
Edge3 = [Edge3; ind, BC_Pt];
elseif (Entity_Index==4)
Edge4 = [Edge4; ind, BC_Pt];
elseif (Entity_Index==5)
Edge5 = [Edge5; ind, BC_Pt];
elseif (Entity_Index==6)
Edge6 = [Edge6; ind, BC_Pt];
else
error('Invalid!');
end
elseif strcmpi(Type,'int_facet')
dof_set = NV{6};
if (dof_set==1)
if (Entity_Index==1)
Face1_1 = [Face1_1; ind, BC_Pt];
elseif (Entity_Index==2)
Face2_1 = [Face2_1; ind, BC_Pt];
elseif (Entity_Index==3)
Face3_1 = [Face3_1; ind, BC_Pt];
elseif (Entity_Index==4)
Face4_1 = [Face4_1; ind, BC_Pt];
else
error('Invalid!');
end
elseif (dof_set==2)
if (Entity_Index==1)
Face1_2 = [Face1_2; ind, BC_Pt];
elseif (Entity_Index==2)
Face2_2 = [Face2_2; ind, BC_Pt];
elseif (Entity_Index==3)
Face3_2 = [Face3_2; ind, BC_Pt];
elseif (Entity_Index==4)
Face4_2 = [Face4_2; ind, BC_Pt];
else
error('Invalid!');
end
else
error('Invalid!');
end
elseif strcmpi(Type,'int_cell')
dof_set = NV{6};
if (dof_set==1)
Cell_1 = [Cell_1; ind, BC_Pt];
elseif (dof_set==2)
Cell_2 = [Cell_2; ind, BC_Pt];
elseif (dof_set==3)
Cell_3 = [Cell_3; ind, BC_Pt];
else
error('Invalid!');
end
else
error('Invalid!');
end
end
Num_E1 = size(Edge1,1);
Num_E2 = size(Edge2,1);
Num_E3 = size(Edge3,1);
Num_E4 = size(Edge4,1);
Num_E5 = size(Edge5,1);
Num_E6 = size(Edge6,1);
Num_F1_1 = size(Face1_1,1);
Num_F2_1 = size(Face2_1,1);
Num_F3_1 = size(Face3_1,1);
Num_F4_1 = size(Face4_1,1);
Num_F1_2 = size(Face1_2,1);
Num_F2_2 = size(Face2_2,1);
Num_F3_2 = size(Face3_2,1);
Num_F4_2 = size(Face4_2,1);
Num_C_1 = size(Cell_1,1);
Num_C_2 = size(Cell_2,1);
Num_C_3 = size(Cell_3,1);
Num_DoF = Num_E1 + Num_E2 + Num_E3 + Num_E4 + Num_E5 + Num_E6 +...
Num_F1_1 + Num_F2_1 + Num_F3_1 + Num_F4_1 + ...
Num_F1_2 + Num_F2_2 + Num_F3_2 + Num_F4_2 + ...
Num_C_1 + Num_C_2 + Num_C_3;
if (Num_DoF~=length(Nodal_Var))
error('Number of DoFs is incorrect!');
end
CHK_EDGE_DOF = max(abs([Num_E1, Num_E2, Num_E3, Num_E4, Num_E5, Num_E6] - Num_E1));
if (CHK_EDGE_DOF~=0)
error('Number of Edge DoFs on each edge is not the same!');
end
CHK_FACE_DOF_1 = max(abs([Num_F1_1, Num_F2_1, Num_F3_1, Num_F4_1] - Num_F1_1));
CHK_FACE_DOF_2 = max(abs([Num_F1_2, Num_F2_2, Num_F3_2, Num_F4_2] - Num_F1_2));
if or(CHK_FACE_DOF_1~=0,CHK_FACE_DOF_2~=0)
error('Number of Face DoFs on each face is not the same!');
end
CHK_CELL_DOF = max(abs([Num_C_1, Num_C_2, Num_C_3] - Num_C_1));
if (CHK_CELL_DOF~=0)
error('Number of Cell DoFs in each set is not the same!');
end
% there are no vertex DoFs
Nodal_Top.V = {[]};
% setup the edge DoFs
Edge1 = sortrows(Edge1,1); % sort based on DoF index
Edge2 = sortrows(Edge2,1);
Edge3 = sortrows(Edge3,1);
Edge4 = sortrows(Edge4,1);
Edge5 = sortrows(Edge5,1);
Edge6 = sortrows(Edge6,1);
DoFs_on_Edge = [Edge1(:,1)'; Edge2(:,1)'; Edge3(:,1)';
Edge4(:,1)'; Edge5(:,1)'; Edge6(:,1)'];
Nodal_Top.E = {DoFs_on_Edge};
% setup the facet (face) DoFs
if ~isempty(Face1_1)
Face1_1 = sortrows(Face1_1,1); % sort based on DoF index
Face2_1 = sortrows(Face2_1,1);
Face3_1 = sortrows(Face3_1,1);
Face4_1 = sortrows(Face4_1,1);
DoFs_on_Face_1 = [Face1_1(:,1)'; Face2_1(:,1)'; Face3_1(:,1)'; Face4_1(:,1)'];
Face1_2 = sortrows(Face1_2,1); % sort based on DoF index
Face2_2 = sortrows(Face2_2,1);
Face3_2 = sortrows(Face3_2,1);
Face4_2 = sortrows(Face4_2,1);
DoFs_on_Face_2 = [Face1_2(:,1)'; Face2_2(:,1)'; Face3_2(:,1)'; Face4_2(:,1)'];
% there are 2 sets of DoFs
% (one for each tangent vector in tangent space of facet)
Nodal_Top.F = {DoFs_on_Face_1, DoFs_on_Face_2};
else
Nodal_Top.F = {[]};
end
% setup the cell (tet) DoFs
if ~isempty(Cell_1)
Cell_1 = sortrows(Cell_1,1); % sort based on DoF index
Cell_2 = sortrows(Cell_2,1);
Cell_3 = sortrows(Cell_3,1);
DoFs_on_Cell_1 = [Cell_1(:,1)'];
DoFs_on_Cell_2 = [Cell_2(:,1)'];
DoFs_on_Cell_3 = [Cell_3(:,1)'];
% there are 3 sets of DoFs (one for each vector component)
Nodal_Top.T = {DoFs_on_Cell_1, DoFs_on_Cell_2, DoFs_on_Cell_3};
else
Nodal_Top.T = {[]};
end
else
error('Not implemented!');
end
Vtx_DoFs = [];
for ii = 1:length(Nodal_Top.V)
Vtx_DoFs = [Vtx_DoFs; Nodal_Top.V{ii}(:)];
end
Edge_DoFs = [];
for ii = 1:length(Nodal_Top.E)
Edge_DoFs = [Edge_DoFs; Nodal_Top.E{ii}(:)];
end
Face_DoFs = [];
for ii = 1:length(Nodal_Top.F)
Face_DoFs = [Face_DoFs; Nodal_Top.F{ii}(:)];
end
Tet_DoFs = [];
for ii = 1:length(Nodal_Top.T)
Tet_DoFs = [Tet_DoFs; Nodal_Top.T{ii}(:)];
end
All_DoFs = [Vtx_DoFs; Edge_DoFs; Face_DoFs; Tet_DoFs];
% final check
Unique_DoFs = unique(All_DoFs);
if (length(All_DoFs)~=length(Unique_DoFs))
error('Not all DoF indices are distinct!');
end
end
|
github
|
eardi/sm-fpca-master
|
write_element_file_nodal_top_string.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Elem_Defn/Generators/Helper_Routines/write_element_file_nodal_top_string.m
| 1,118 |
utf_8
|
e029b77686b94c0616f6cd395d7dc91d
|
function Nodal_Sets_str = write_element_file_nodal_top_string(Nodal_Sets,TAB)
%write_element_file_nodal_top_string
%
% This creates a string representing the sets of DoF indices.
% Copyright (c) 10-10-2016, Shawn W. Walker
Nodal_Sets_str = []; % init
for ii = 1:length(Nodal_Sets)-1
DoF_set = Nodal_Sets{ii};
Nodal_Sets_str = write_one_set(DoF_set,TAB,Nodal_Sets_str);
Nodal_Sets_str = [Nodal_Sets_str, ',...\n'];
end
DoF_set = Nodal_Sets{end};
Nodal_Sets_str = write_one_set(DoF_set,TAB,Nodal_Sets_str);
Nodal_Sets_str = [Nodal_Sets_str, '...'];
end
function DoF_set_string = write_one_set(DoF_set,TAB,DoF_set_string)
DoF_set_string = [DoF_set_string, TAB, '['];
for rr = 1:size(DoF_set,1)
for cc = 1:size(DoF_set,2)-1
DoF_set_string = [DoF_set_string, num2str(DoF_set(rr,cc)), ', '];
end
if (rr < size(DoF_set,1))
DoF_set_string = [DoF_set_string, num2str(DoF_set(rr,end)), ';\n'];
DoF_set_string = [DoF_set_string, TAB, ' '];
else
DoF_set_string = [DoF_set_string, num2str(DoF_set(rr,end)), ']'];
end
end
end
|
github
|
eardi/sm-fpca-master
|
basis_symm_matrix_polys_deg_k.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Elem_Defn/Generators/Helper_Routines/basis_symm_matrix_polys_deg_k.m
| 2,048 |
utf_8
|
29f9d893a92766a0988cb1decd000514
|
function [basis, const_basis] = basis_symm_matrix_polys_deg_k(indep_vars,deg_k,mat_size,exact)
%basis_symm_matrix_polys_deg_k
%
% This returns a set of symmetric matrix-valued basis polynomials
% (of degree <= k) in the given independent variables.
%
% indep_vars = col. vector of symbolic independent vars;
% all must be distinct!
% deg_k = maximum degree of basis polynomials.
% mat_size = size of matrix.
% exact = boolean
% true: degree of polynomial basis functions is *exactly* deg_k.
% false: (default) degree of basis functions is <= deg_k.
% Copyright (c) 03-22-2018, Shawn W. Walker
if (nargin==3)
exact = false;
end
% scalar basis functions
scalar_basis = basis_polys_deg_k(indep_vars,deg_k,exact);
num_scalar_basis = length(scalar_basis);
% tensor product the scalar basis functions
const_basis = get_symm_mat_basis(mat_size);
num_basis_of_symm_mat = mat_size * (mat_size+1)/2;
if (length(const_basis)~=num_basis_of_symm_mat)
error('These should match!');
end
num_mat_basis = num_basis_of_symm_mat * num_scalar_basis;
basis(num_mat_basis).func = []; % init
for mm = 1:num_basis_of_symm_mat
for ii = 1:num_scalar_basis
scalar_func = scalar_basis(ii).func;
% form symmetric matrix basis function
mat_func = const_basis(mm).mat * scalar_func;
basis(ii + (mm-1)*num_scalar_basis).func = mat_func;
end
end
end
function const_basis = get_symm_mat_basis(mat_size)
num_basis_of_symm_mat = mat_size * (mat_size+1)/2;
const_basis(num_basis_of_symm_mat).mat = [];
% init
zero_mat = zeros(mat_size,mat_size);
% get diagonal component bases
for kk = 1:mat_size
MB = zero_mat;
MB(kk,kk) = 1;
const_basis(kk).mat = MB;
end
INDEX = mat_size;
% get off-diagonal component bases
for ii = 1:mat_size
for jj = ii+1:mat_size
MB = zero_mat;
MB(ii,jj) = 1;
INDEX = INDEX + 1;
const_basis(INDEX).mat = (1/2)*(MB + MB');
end
end
end
|
github
|
eardi/sm-fpca-master
|
Permute_Nedelec_1stKind_On_Simplex_Nodal_Variables.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Elem_Defn/Nodal_Variables/Permute_Nedelec_1stKind_On_Simplex_Nodal_Variables.m
| 4,466 |
utf_8
|
a727f6f2f783ac5a706fb1e9a3752056
|
function Permute_Nodal_Var = Permute_Nedelec_1stKind_On_Simplex_Nodal_Variables(Cell,DoF_Perm,Perm_Tet,...
Sym_Perm_Map,Jacobian_Matrix,Nodal_Var)
%Permute_Nedelec_1stKind_On_Simplex_Nodal_Variables
%
% This permutes the Nodal Variable Data.
% Copyright (c) 11-02-2016, Shawn W. Walker
% % need it symbolically (this is my F_{\tilde{T}} map from \hat{T} --> \tilde{T}
% Sym_Perm_Map = FELSymFunc(Sym_Func_Temp,std_vars);
Permute_Nodal_Var = Nodal_Var; % init
J_inv = inv(Jacobian_Matrix);
det_J = det(Jacobian_Matrix);
% DoF_Perm : \hat{T} --> \tilde{T}
Num_DoFs = length(DoF_Perm);
% map and permute nodal-var data
for hat_ind = 1:Num_DoFs
tilde_ind = DoF_Perm(hat_ind);
NV_tilde_Data = Nodal_Var(tilde_ind).Data;
NV_hat_Data = Nodal_Var(hat_ind).Data; % init!
NV_Type = NV_tilde_Data{3};
% error check
if ~strcmpi(NV_hat_Data{3},NV_Type)
error('Nodal types are different!');
end
% BEGIN: modify Nodal Variable data on \tilde{T} to be defined on \hat{T}
% convert dual function string to useable format
func_handle_str = ['@(x,y,z) ', NV_tilde_Data{2}];
func_handle = str2func(func_handle_str);
sym_dual_func = sym(func_handle);
Dual_Func_tilde = FELSymFunc(sym_dual_func);
% modify dual function
Dual_Func_tilde = Dual_Func_tilde.Rename_Independent_Vars({'x', 'y', 'z'},{'x_t', 'y_t', 'z_t'});
Mapped_Dual_Func = Dual_Func_tilde.Compose_Function(Sym_Perm_Map);
Entity_tilde = NV_tilde_Data{4};
% Note: the barycentric coordinates are already correct; accounted for by DoF_Perm
if strcmpi(NV_Type,'int_edge')
% get corresponding entity on \hat{T}
Entity_hat = inverse_entity_map(Perm_Tet.Edge,Entity_tilde);
if (Entity_hat~=NV_hat_Data{4})
error('Permutation data not correct!');
end
% get ratio of edge lengths
edge_ratio = Cell.Edge(Entity_tilde).Measure / Cell.Edge(Entity_hat).Measure;
% multiply by jacobian stuff
Dual_Func_hat_sym = edge_ratio * J_inv * Mapped_Dual_Func.Func;
% remake into a string
NV_hat_Data{2} = make_sym_vec_func_str(Dual_Func_hat_sym);
elseif strcmpi(NV_Type,'int_facet')
% get corresponding entity on \hat{T}
Entity_hat = inverse_entity_map(Perm_Tet.Face,Entity_tilde);
if (Entity_hat~=NV_hat_Data{4})
error('Permutation data not correct!');
end
% multiply by jacobian stuff
Dual_Func_hat_sym = J_inv * Mapped_Dual_Func.Func;
% remake into a string
NV_hat_Data{2} = make_sym_vec_func_str(Dual_Func_hat_sym);
elseif strcmpi(NV_Type,'int_cell')
% get corresponding entity on \hat{T}
Entity_hat = inverse_entity_map(Perm_Tet.Tet,Entity_tilde);
if (Entity_hat~=NV_hat_Data{4})
error('Permutation data not correct!');
end
% multiply by jacobian stuff
Dual_Func_hat_sym = det_J * J_inv * Mapped_Dual_Func.Func;
% remake into a string
NV_hat_Data{2} = make_sym_vec_func_str(Dual_Func_hat_sym);
else
error('Invalid!');
end
% END: modify Nodal Variable data on \tilde{T} to be defined on \hat{T}
Permute_Nodal_Var(hat_ind).Data = NV_hat_Data;
end
end
function Entity_inverse_index = inverse_entity_map(Perm_Entity,Entity_index)
[TF,LOC] = ismember(Entity_index,Perm_Entity);
Entity_inverse_index = LOC(TF);
if (Perm_Entity(Entity_inverse_index)~=Entity_index)
error('Entity permutation not correct!');
end
end
function Func_Str = make_sym_vec_func_str(Sym_Func)
Num_Comp = length(Sym_Func);
if (Num_Comp==1)
Func_Str = ['[', char(Sym_Func), ']'];
elseif (Num_Comp==2)
Func_Str = ['[', char(Sym_Func(1)), '; ', char(Sym_Func(2)), ']'];
elseif (Num_Comp==3)
Func_Str = ['[', char(Sym_Func(1)), '; ', char(Sym_Func(2)), '; ', char(Sym_Func(3)), ']'];
elseif (Num_Comp==4)
Func_Str = ['[', char(Sym_Func(1)), '; ', char(Sym_Func(2)), '; ', char(Sym_Func(3)), '; ', char(Sym_Func(4)), ']'];
elseif (Num_Comp==5)
Func_Str = ['[', char(Sym_Func(1)), '; ', char(Sym_Func(2)), '; ', char(Sym_Func(3)), '; ', char(Sym_Func(4)), '; ', char(Sym_Func(5)), ']'];
else
error('Not implemented!');
end
end
|
github
|
eardi/sm-fpca-master
|
demo_test_dirs.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Demo/demo_test_dirs.m
| 2,611 |
utf_8
|
1d6b238662b35218ae37d950eb337e19
|
function Unit_Test_Dirs = demo_test_dirs()
%demo_test_dirs
%
% This outputs a list of directories containing the demos.
% Copyright (c) 05-07-2019, Shawn W. Walker
% get the main directory that this function is in!
MFN = mfilename('fullpath');
Main_Dir = fileparts(MFN);
% define demo dirs
% init
Unit_Test_Dirs.str1 = fullfile(Main_Dir, 'Closest_Point_Sphere');
Unit_Test_Dirs.str2 = [];
Unit_Test_Dirs.str3 = [];
% next!
str1 = fullfile(Main_Dir, 'Curved_Domain_2D');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
% str1 = fullfile(Main_Dir, 'CiarletRaviart');
% Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'DoFmap_Generation', 'Dim_2');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'EWOD');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Finite_Element_Space_2D');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Finite_Element_Space_On_1D_Subdomain');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Heat_Eqn_On_A_Surface');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Image_Processing');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Interp_2D');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Laplace_1D');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Laplace_Beltrami_Open_Surface');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Laplace_On_Cube_3D');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Local_FE_Matrix');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Mesh_Gen_With_Solving_PDE');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Mesh_Smoothing_2D');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Point_Search_Domain_2D');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Simple_Elasticity_3D');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Stokes_2D');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
end
function New_Dirs = append_dir(Dirs,str1,str2,str3)
DS.str1 = str1;
DS.str2 = str2;
DS.str3 = str3;
Num = length(Dirs);
New_Dirs = Dirs; % init
New_Dirs(Num+1) = DS;
end
|
github
|
eardi/sm-fpca-master
|
Execute_Laplace_On_Cube_3D.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Demo/Laplace_On_Cube_3D/Execute_Laplace_On_Cube_3D.m
| 4,920 |
utf_8
|
6e31629a01295f97ccdab78f7d76c6b7
|
function status = Execute_Laplace_On_Cube_3D()
%Execute_Laplace_On_Cube_3D
%
% Demo code for Laplace's equation on 3-D cube.
% Copyright (c) 06-25-2012, Shawn W. Walker
% BEGIN: define mesh of cube
disp(' ');
disp('Create Cube Mesh:');
tic
Num_Pts = 20+1; % max is 70+1 on my laptop (just barely worked!)
% Number of Free DoFs = 328509
% can go much higher with AGMG!
[Omega_Tet, Omega_Vertex] = regular_tetrahedral_mesh(Num_Pts,Num_Pts,Num_Pts);
Mesh = MeshTetrahedron(Omega_Tet, Omega_Vertex, 'Omega');
%Mesh = Mesh.Reorder;
toc
clear Omega_Tet Omega_Vertex;
% END: define mesh of cube
% define subdomains
Bdy_Faces = Mesh.freeBoundary();
Mesh = Mesh.Append_Subdomain('2D','Bdy',Bdy_Faces);
% define function spaces (i.e. the DoFmaps)
P1_Space_DoFmap = uint32(Mesh.ConnectivityList);
% assemble
disp(' ');
disp('Assemble Stiffness matrix:');
tic
FEM = DEMO_mex_Laplace_On_Cube_3D_assemble([],Mesh.Points,P1_Space_DoFmap,[],[],P1_Space_DoFmap);
toc
A_from_scratch = FEM(1).MAT;
% doing re-assembly is at least 2 times (and up to 3 times) faster!
disp(' ');
disp('Assemble AGAIN!:');
tic
FEM = DEMO_mex_Laplace_On_Cube_3D_assemble(FEM,Mesh.Points,P1_Space_DoFmap,[],[],P1_Space_DoFmap);
toc
ERR1 = abs(FEM(1).MAT - A_from_scratch);
ERR1 = max(ERR1(:));
disp('Difference between Original Matrix and Re-assembled Matrix:');
ERR1
current_file = mfilename('fullpath');
Current_Dir = fileparts(current_file);
RefFEMDataFileName = fullfile(Current_Dir,'Demo_Laplace_On_Cube_3D_REF_Data.mat');
% FEM_REF = FEM;
% save(RefFEMDataFileName,'FEM_REF');
load(RefFEMDataFileName);
% do some checks
disp(' ');
disp('Summing the P1 stiffness matrix A should be close to 0. Error is:');
sum(FEM(1).MAT(:)) - 0
disp('Setup Laplace equation with Dirichlet conditions on Bdy:');
Soln = zeros(Mesh.Num_Vtx,1); % init
A = FEM(1).MAT;
disp('----> set u = sin(2*pi*x) + cos(2*pi*y) + sin(2*pi*z) on Bdy.');
% get Bdy Degrees-of-Freedom (DoF)
Bdy_Nodes = unique(Bdy_Faces(:));
% get Bdy DoF coordinates
Bdy_XC = Mesh.Points(Bdy_Nodes,:);
Soln(Bdy_Nodes,1) = sin(2*pi*Bdy_XC(:,1)) + cos(2*pi*Bdy_XC(:,2)) + sin(2*pi*Bdy_XC(:,3));
RHS = 0*Soln;
RHS = RHS - A * Soln;
% get the free nodes of the system
All_Vtx_Indices = (1:1:Mesh.Num_Vtx)';
FreeNodes = setdiff(All_Vtx_Indices,Bdy_Nodes);
disp(' ');
disp(['Size of A = ', num2str(size(A))]);
disp(['Number of Free DoFs = ', num2str(length(FreeNodes))]);
disp(' ');
MI = MEM_Info(A);
MEM_A = MI.bytes / (2^20);
disp(['Memory allocation for A = ', num2str(MEM_A), ' MB']);
disp(' ');
disp('Solve linear system with backslash:');
tic
Soln(FreeNodes,1) = A(FreeNodes,FreeNodes) \ RHS(FreeNodes,1);
toc
% % Note: you must have AGMG installed to run this!
% disp(' ');
% TOL = 1e-8;
% disp(['Solve linear system with AGMG with TOL = ', num2str(TOL,'%1.2G'), ':']);
% Soln_AGMG = Soln;
% tic
% Soln_AGMG(FreeNodes,1) = agmg(A(FreeNodes,FreeNodes),RHS(FreeNodes,1),[],TOL);
% toc
% Soln = Soln_AGMG;
% Soln_Diff = max(abs(Soln - Soln_AGMG));
% disp(' ');
% disp('Max difference between backslash and AGMG:');
% Soln_Diff
% % Note: you must have Pardiso installed to run this! Almost as good as backslash
% disp(' ');
% disp(['Solve linear system with Pardiso (min degree ordering):']);
% Soln_Pardiso = Soln;
% info = pardisoinit(11,0);
% info.iparm(2) = 0; % min degree ordering
% info.iparm(3) = 2; % num cores
% tic
% info = pardisoreorder(A(FreeNodes,FreeNodes),info,true);
% info = pardisofactor(A(FreeNodes,FreeNodes),info,true);
% [Soln_Pardiso(FreeNodes,1), info] = pardisosolve(A(FreeNodes,FreeNodes),RHS(FreeNodes,1),info,true);
% toc
% pardisofree(info);
% clear info;
% Soln_Diff = max(abs(Soln - Soln_Pardiso));
% disp(' ');
% disp('Max difference between backslash and Pardiso:');
% Soln_Diff
% % Note: you must have SuperLU installed to run this! Really slow compared to backslash
% disp(' ');
% disp(['Solve linear system with SuperLU:']);
% Soln_SuperLU = Soln;
% tic
% Soln_SuperLU(FreeNodes,1) = lusolve(A(FreeNodes,FreeNodes),RHS(FreeNodes,1));
% toc
% Soln_Diff = max(abs(Soln - Soln_SuperLU));
% disp(' ');
% disp('Max difference between backslash and SuperLU:');
% Soln_Diff
figure;
h1 = trisurf(Bdy_Faces,Mesh.Points(:,1),Mesh.Points(:,2),Mesh.Points(:,3),Soln(:,1));
title('Boundary Mesh and Boundary Condition','FontSize',12);
set(gca,'FontSize',14);
AX = [0 1 0 1 0 1];
axis(AX);
axis equal;
axis(AX);
status = 0; % init
% compare to reference data
ERRORS = zeros(length(FEM),1);
for ind = 1:length(FEM)
ERRORS(ind) = max(abs(FEM(ind).MAT(:) - FEM_REF(ind).MAT(:)));
if (ERRORS(ind) > 1e-13)
disp(['Test Failed for FEM(', num2str(ind), ').MAT...']);
status = 1;
end
end
end
function MI = MEM_Info(A)
MI = whos;
end
|
github
|
eardi/sm-fpca-master
|
Execute_EWOD_FalkWalker.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Demo/EWOD/Execute_EWOD_FalkWalker.m
| 9,276 |
utf_8
|
8a44d4c2ac9cd1e18f12669f9cf6e9ea
|
function status = Execute_EWOD_FalkWalker()
%Execute_EWOD_FalkWalker
%
% Demo code for solving the EWOD problem (using the formulation by Falk
% and Walker, 2013).
% Copyright (c) 12-05-2017, Shawn W. Walker
Main_Dir = fileparts(mfilename('fullpath'));
% define initial disk surface
Refine_Level = 5;
[Tri, Pts] = triangle_mesh_of_disk([0 0],1,Refine_Level);
Mesh = MeshTriangle(Tri, Pts, 'Omega');
% add the open boundary
BDY = Mesh.freeBoundary();
Mesh = Mesh.Append_Subdomain('1D','Gamma',BDY);
clear BDY;
%Mesh.Plot;
% define parameters
alpha = 0.01;
beta = 1;
dt = 0.1;
Num_Steps = 30;
% create GeoElementSpace
P1_RefElem_2D = ReferenceFiniteElement(lagrange_deg1_dim2());
G_Space = GeoElementSpace('G_h',P1_RefElem_2D,Mesh);
G_Space = G_Space.Set_DoFmap(Mesh,uint32(Mesh.ConnectivityList));
G_Space = G_Space.Append_Fixed_Subdomain(Mesh,'Gamma');
% store mesh vertex coordinates
x_h_i = G_Space.Get_Mapping_For_Piecewise_Linear_Mesh(Mesh); % initialize
x_h_evolve(Num_Steps+1).data = [];
x_h_evolve(1).data = x_h_i; % store it
% define FE spaces
BDM1_RefElem = ReferenceFiniteElement(brezzi_douglas_marini_deg1_dim2());
V_Space = FiniteElementSpace('V_h', BDM1_RefElem, Mesh, 'Omega');
V_DoFmap = mex_EWOD_DoF_Alloc_V_h(uint32(Mesh.ConnectivityList));
V_Space = V_Space.Set_DoFmap(Mesh,uint32(V_DoFmap));
clear V_DoFmap;
P0_RefElem = ReferenceFiniteElement(lagrange_deg0_dim2());
Q_Space = FiniteElementSpace('Q_h', P0_RefElem, Mesh, 'Omega');
Q_DoFmap = (1:1:Mesh.Num_Cell)'; % only one DoF per element
Q_Space = Q_Space.Set_DoFmap(Mesh,uint32(Q_DoFmap));
clear Q_DoFmap;
P1_RefElem = ReferenceFiniteElement(lagrange_deg1_dim1());
M_Space = FiniteElementSpace('M_h', P1_RefElem, Mesh, 'Gamma');
M_DoFmap = mex_EWOD_DoF_Alloc_M_h(uint32(Mesh.Get_Global_Subdomain('Gamma')));
M_Space = M_Space.Set_DoFmap(Mesh,uint32(M_DoFmap));
Y_Space = FiniteElementSpace('M_h', P1_RefElem, Mesh, 'Gamma', 2);
Y_Space = Y_Space.Set_DoFmap(Mesh,uint32(M_DoFmap)); % can reuse it!
clear M_DoFmap;
% initialize u_h:
u_h = zeros(V_Space.num_dof,1);
% BEGIN: find the mapping from M_h and Y_h nodes to G_h nodes
disp('create Quadtree...');
BB = 2*[-1.001, 1.001, -1.001, 1.001]; % bounding box
QT = mexQuadtree(x_h_i,BB);
% get coordinates of DoFs in M_h and Y_h
M_Points = M_Space.Get_DoF_Coord(Mesh);
Y_Points = Y_Space.Get_DoF_Coord(Mesh);
% find the mapping via closest point
[M_h_to_G_h, QT_dist] = QT.kNN_Search(M_Points,1);
if max(QT_dist) > 1e-14
error('Points should be right on top of each other.');
end
[Y_h_to_G_h, QT_dist] = QT.kNN_Search(Y_Points,1);
if max(QT_dist) > 1e-14
error('Points should be right on top of each other.');
end
delete(QT); % delete quadtree object
% END: find the mapping from M_h and Y_h nodes to G_h nodes
% get the DoF indices (of G_h) that are NOT on \Gamma
G_h_Free_DoFs = G_Space.Get_Free_DoFs(Mesh,'all');
% compute embedding data
Domain_Names = {'Omega'; 'Gamma'};
Omega_Embed = Mesh.Generate_Subdomain_Embedding_Data(Domain_Names);
% must choose an orientation of the mesh facets (for BDM_1 space)
Edges = Mesh.edges;
[~, Omega_Orient] = Mesh.Get_Facet_Info(Edges);
% time-stepping
for ii = 1:Num_Steps
%
disp('-------------------------------------------------------');
disp(['Time Index: ', num2str(ii), ' of ', num2str(Num_Steps)]);
% assemble
tic
FEM = mex_MatAssem_EWOD_FalkWalker([],x_h_i,G_Space.DoFmap,Omega_Orient,Omega_Embed,...
G_Space.DoFmap,M_Space.DoFmap,Q_Space.DoFmap,V_Space.DoFmap,Y_Space.DoFmap);
toc
% put FEM into a nice object to make accessing the matrices easier
EWOD_Mats = FEMatrixAccessor('EWOD',FEM);
clear FEM;
% pull out the matrices
M = EWOD_Mats.Get_Matrix('M');
K = EWOD_Mats.Get_Matrix('K');
B = EWOD_Mats.Get_Matrix('B');
C = EWOD_Mats.Get_Matrix('C');
D = EWOD_Mats.Get_Matrix('D');
chi = EWOD_Mats.Get_Matrix('chi');
% define EWOD forcing as function over \R^2
%E_exact = @(x,y) 1 - x.^2;
E_exact = @(x,y) 3*ewod_force_1(x,y);
% interpolate over \Omega
E_Omega_h = E_exact(x_h_i(:,1),x_h_i(:,2));
% extract the part that is on \Gamma
E_h = E_Omega_h(M_h_to_G_h,1);
disp('Solve the EWOD system:');
% make the big matrix
VN = V_Space.num_dof;
QN = Q_Space.num_dof;
YN = 2*Y_Space.num_dof;
MN = M_Space.num_dof;
MAT = [((alpha/dt)+beta)*M, -B', sparse(VN,YN), C';
-B, sparse(QN,QN), sparse(QN,YN), sparse(QN,MN);
sparse(YN,VN), sparse(YN,QN), K, -D';
C, sparse(MN,QN), -(1/dt)*D, sparse(MN,MN)];
RHS = [(alpha/dt)*M*u_h - C'*E_h; zeros(QN,1); zeros(YN,1); -(1/dt)*chi];
% use backslash to solve
Soln = MAT \ RHS;
% parse the solution
u_h = Soln(1:VN,1);
p_h = Soln(VN+1:VN+QN,1);
x_h_new_bdy = zeros(YN/2,2);
x_h_new_bdy(:) = Soln(VN+QN+1:VN+QN+YN,1);
lambda_h = Soln(VN+QN+YN+1:end,1);
% BEGIN: update \Omega
x_h_old_bdy = x_h_i(Y_h_to_G_h,:);
Displace_bdy = x_h_new_bdy - x_h_old_bdy; % bdy displacement
% init domain displacement
Displace = G_Space.Get_Zero_Function;
Displace(Y_h_to_G_h,:) = Displace_bdy;
D_Soln = Displace(:);
% solve for Laplace smoothing
A = EWOD_Mats.Get_Matrix('A');
R1 = -A * D_Soln; % set boundary conditions
D_Soln(G_h_Free_DoFs,1) = A(G_h_Free_DoFs,G_h_Free_DoFs) \ R1(G_h_Free_DoFs,1);
Displace(:) = D_Soln; % put back into two-column matrix format
Inf_Norm_Displace = max(abs(Displace(:)));
disp(['L^\infty norm of \Omega Displacement: ', num2str(Inf_Norm_Displace,'%1.10G')]);
% update domain coordinates
x_h_new = x_h_i + Displace;
% END: update \Omega
% store solution
x_h_evolve(ii+1).data = x_h_new; % store it
x_h_i = x_h_new; % update for next time-step
end
% plot solution
disp('Plot Droplet Evolution:');
FH_evol = figure('Renderer','painters','PaperPositionMode','auto','Color','w');
BDY = Mesh.Get_Global_Subdomain('Gamma');
hold on;
time_vec = [1, 2, 5, length(x_h_evolve)];
for tt = 1:length(time_vec)
em = edgemesh(BDY,x_h_evolve(time_vec(tt)).data);
set(em,'LineWidth',1.4);
end
hold off;
title('domain \Omega at four time steps');
%title('plotomega');
xlabel('X');
ylabel('Y');
grid on;
%set(gca,'FontSize',10);
AX = [-2 2 -1 1];
axis(AX);
axis equal;
axis(AX);
view(2);
% plot solution
disp('Plot Droplet Domain at Final Time:');
FH_x_h = figure('Renderer','painters','PaperPositionMode','auto','Color','w');
tm = trimesh(Mesh.ConnectivityList,x_h_i(:,1),x_h_i(:,2),0*x_h_i(:,2));
set(tm,'EdgeColor','k');
hold on;
BDY = Mesh.Get_Global_Subdomain('Gamma');
em = edgemesh(BDY,x_h_i);
set(em,'LineWidth',1.5);
hold off;
title('domain \Omega at final time');
%title('plotomega');
xlabel('X');
ylabel('Y');
grid on;
%set(gca,'FontSize',10);
AX = [-1.7 1.7 -0.7 0.7];
axis(AX);
axis equal;
axis(AX);
view(2);
% Plot the \lambda solution:
Gamma_X = x_h_i(M_h_to_G_h,:);
FH_lambda_h = figure('Renderer','painters','PaperPositionMode','auto','Color','w');
p2 = edgemesh(M_Space.DoFmap, [Gamma_X, 0*Gamma_X(:,1)], lambda_h);
set(p2,'LineWidth',2.0);
shading interp;
title('Color plot of \lambda_h on \Gamma');
%title('plotlam');
xlabel('X');
ylabel('Y');
grid on;
axis(AX);
axis equal;
axis(AX);
colorbar;
view(2);
% error check
RefErrorDataFileName = fullfile(Main_Dir,'FEL_Execute_EWOD_FalkWalker_REF_Data.mat');
% save(RefErrorDataFileName,'x_h_i');
REF_DATA = load(RefErrorDataFileName);
% check the difference with previous run
x_h_i_REF = REF_DATA.x_h_i;
ERR_CHK = abs(x_h_i_REF - x_h_i);
ERR_CHK = max(ERR_CHK(:));
% different computers should compute the same errors (up to round-off!)
status = 0; % init
if (max(ERR_CHK) > 1e-10)
disp('EWOD error check failed!');
ERR_CHK
status = 1;
end
% %--------------------------------------------------
%
% % code to generate plots for FELICITY paper
% FigDir = 'C:\FILES\LaTex\Papers_New\FELICITY_SISC_Paper\Figures';
% %FigDir = 'C:\FILES\FELICITY\Wiki\Images';
%
%
% % set filename
% SaveFig = 'EWOD_FalkWalker_x_h_bdy_Evolve';
% FN = fullfile(FigDir,SaveFig);
% %export_fig(FN, '-pdf', '-eps', '-transparent');
% %export_fig(FN, '-pdf', '-transparent');
%
% print(FH_evol,'-depsc',FN); % color
% %print(FH_evol,'-djpeg',FN); % color
%
%
% % set filename
% SaveFig = 'EWOD_FalkWalker_Omega_Final';
% FN = fullfile(FigDir,SaveFig);
% %export_fig(FN, '-pdf', '-eps', '-transparent');
% %export_fig(FN, '-pdf', '-transparent');
%
% print(FH_x_h,'-depsc',FN); % color
% %print(FH_x_h,'-djpeg',FN); % color
%
%
% % set filename
% SaveFig = 'EWOD_FalkWalker_lambda_h_Final';
% FN = fullfile(FigDir,SaveFig);
% %export_fig(FN, '-pdf', '-eps', '-transparent');
% %export_fig(FN, '-pdf', '-transparent');
%
% %print(FH,'-deps',FN); % black and white
% print(FH_lambda_h,'-depsc',FN); % color
% %print(FH_lambda_h,'-djpeg',FN); % color
%
% %--------------------------------------------------
end
function E_exact = ewod_force_1(x,y)
% like the electrode case
EL = 0.5*((2/pi)*atan( (x+0.5)/0.02) - 1);
ER = 0.5*((2/pi)*atan(-(x-0.5)/0.02) - 1);
E_exact = EL + ER;
end
|
github
|
eardi/sm-fpca-master
|
matrix_assembly_unit_test_dirs.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/matrix_assembly_unit_test_dirs.m
| 4,559 |
utf_8
|
ab821bb181614a747c0d71a58bbd5bc9
|
function Unit_Test_Dirs = matrix_assembly_unit_test_dirs()
%matrix_assembly_unit_test_dirs
%
% This outputs a list of directories containing the unit tests.
% Copyright (c) 04-05-2018, Shawn W. Walker
% get the main directory that this function is in!
MFN = mfilename('fullpath');
Main_Dir = fileparts(MFN);
% define unit test dirs
% init
Unit_Test_Dirs.str1 = fullfile(Main_Dir, 'Unit_Test', 'Assembly', 'Assemble_Subset_2D');
Unit_Test_Dirs.str2 = [];
Unit_Test_Dirs.str3 = [];
% next!
str1 = fullfile(Main_Dir, 'Unit_Test', 'Dim_1');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Unit_Test', 'Dim_2');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Unit_Test', 'Dim_3');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Unit_Test', 'Codim_1', 'Coarse_Square');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Unit_Test', 'Codim_1', 'Refined_Square');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Unit_Test', 'Hdiv', 'RT0');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Unit_Test', 'Hdiv', 'RT0_Codim_1');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Unit_Test', 'Hdiv', 'RTk_Surface');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Unit_Test', 'Hdiv', 'RT1_Dim3');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Unit_Test', 'Hdiv', 'BDM1');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Unit_Test', 'Hdiv', 'BDM1_Codim_1');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
% str1 = fullfile(Main_Dir, 'Unit_Test', 'Hdivdiv', 'HHJk');
% Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
disp('SWW: put in unit test for HHJ!!!!');
str1 = fullfile(Main_Dir, 'Unit_Test', 'Lagrange');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Unit_Test', 'Hcurl', 'Nedelec1stKind_Deg1_Dim2');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Unit_Test', 'Hcurl', 'Nedelec1stKind_Deg1_Dim2');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Unit_Test', 'Hcurl', 'Nedelec1stKind_Deg2_Dim3');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Unit_Test', 'Hcurl', 'Nedelec1stKind_Deg2_Dim3');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Unit_Test', 'Hessian', 'Dim_1');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Unit_Test', 'Hessian', 'Dim_2');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Unit_Test', 'Hessian', 'Dim_3');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Unit_Test', 'Hessian', 'TopDim_1_GeoDim_2');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Unit_Test', 'Hessian', 'TopDim_1_GeoDim_3');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Unit_Test', 'Hessian', 'TopDim_2_GeoDim_3');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Unit_Test', 'Mesh_Size', 'Dim_1');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Unit_Test', 'Multiple_Subdomains', 'Embedding_Dim_1');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Unit_Test', 'Multiple_Subdomains', 'Embedding_Dim_2');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Unit_Test', 'Multiple_Subdomains', 'Embedding_Dim_3');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Unit_Test', 'Multiple_Subdomains', 'Mixed_Geometry_1');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Unit_Test', 'Symbolic_Constants', 'Dim_2');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Unit_Test', 'Symbolic_Constants', 'Mixed_Domains');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
end
function New_Dirs = append_dir(Dirs,str1,str2,str3)
DS.str1 = str1;
DS.str2 = str2;
DS.str3 = str3;
Num = length(Dirs);
New_Dirs = Dirs; % init
New_Dirs(Num+1) = DS;
end
|
github
|
eardi/sm-fpca-master
|
Update_GeomFunc_Options_From_Basis_Functions.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Level_3/@FELSpaces/Update_GeomFunc_Options_From_Basis_Functions.m
| 4,379 |
utf_8
|
9d49f830959cd57a38693c9727ebc5ae
|
function obj = Update_GeomFunc_Options_From_Basis_Functions(obj,Integration_Index)
%Update_GeomFunc_Options_From_Basis_Functions
%
% This updates what needs to be computed in the C++ code for the geometric
% functions in order to compute all the basis function transformations.
% Copyright (c) 01-23-2014, Shawn W. Walker
All_BF = obj.Integration(Integration_Index).BasisFunc;
BF_Names = All_BF.keys;
% update the internal geometric function of each basis function
for bi = 1:length(BF_Names)
% parse out
Current_BasisFunc = All_BF(BF_Names{bi});
Basis_Func_Opt = Current_BasisFunc.Opt;
% update the geometric options in the GeomFunc associated with the basis function
Current_BasisFunc.GeomFunc.Opt = Current_BasisFunc.FuncTrans.Update_Geometric_Options(...
Basis_Func_Opt,Current_BasisFunc.GeomFunc.Opt);
% save it
All_BF(BF_Names{bi}) = Current_BasisFunc;
end
% next, update the Domain of Integration (DoI) geometric function, if necessary.
DoI_GeomFunc = obj.Integration(Integration_Index).DoI_Geom;
[All_BF, DoI_GeomFunc] = enforce_consistent_geometric_function(BF_Names,All_BF,DoI_GeomFunc);
% don't forget to put it back into the object
obj.Integration(Integration_Index).DoI_Geom = DoI_GeomFunc;
% now update any other geometric functions, if necessary
GF_Names = obj.Integration(Integration_Index).GeomFunc.keys;
for gi = 1:length(GF_Names)
Single_GF = obj.Integration(Integration_Index).GeomFunc(GF_Names{gi});
[All_BF, Single_GF] = enforce_consistent_geometric_function(BF_Names,All_BF,Single_GF);
% don't forget to put it back into the object
obj.Integration(Integration_Index).GeomFunc(GF_Names{gi}) = Single_GF;
end
% don't forget to put it back into the object
obj.Integration(Integration_Index).BasisFunc = All_BF;
% disp('==========BEGIN GROUP==============');
% disp(' ');
%
% % PRINT the internal geometric function of each basis function
% for bi = 1:length(BF_Names)
%
% % parse out
% Current_BasisFunc = All_BF(BF_Names{bi});
% disp('==========START==============');
% Current_BasisFunc.Func_Name
% Current_BasisFunc.GeomFunc
% end
end
function [All_BF, GeomFunc] = enforce_consistent_geometric_function(BF_Names,All_BF,GeomFunc)
% make sure the individual basis functions that use the same
% geometric function *share* the same options
for bi = 1:length(BF_Names)
Current_BasisFunc = All_BF(BF_Names{bi});
for oi = 1:length(BF_Names)
if (oi~=bi)
Other_BasisFunc = All_BF(BF_Names{oi});
% if the basis function's geom_func matches the other geom_func
if strcmp(Current_BasisFunc.GeomFunc.CPP.Identifier_Name,Other_BasisFunc.GeomFunc.CPP.Identifier_Name)
% OR the options together
Current_BasisFunc.GeomFunc = Current_BasisFunc.GeomFunc.OR_Options(Other_BasisFunc.GeomFunc);
All_BF(BF_Names{bi}) = Current_BasisFunc;
end
end
end
end
% sometimes, the geometric function for a basis function IS THE SAME as another
% geometric function, such as the integration domain's (DoI) geometric function or some
% other (sub-)domain's geometric function. In this case, we must ensure that
% both versions (the domain version and the basis function version) have the same options!
Domain_GF_Name = GeomFunc.CPP.Identifier_Name;
for bi = 1:length(BF_Names)
Current_BasisFunc = All_BF(BF_Names{bi});
% if the basis function's geom_func matches the domain geom_func
if strcmp(Domain_GF_Name,Current_BasisFunc.GeomFunc.CPP.Identifier_Name)
% OR the options together
GeomFunc = GeomFunc.OR_Options(Current_BasisFunc.GeomFunc);
end
end
% so now the GeomFunc contains all the options for the domain and ALL of the basis functions
% make sure the basis function versions have the SAME geom options as the domain version
for bi = 1:length(BF_Names)
Current_BasisFunc = All_BF(BF_Names{bi});
% if the basis function's geom_func matches the domain geom_func
if strcmp(Domain_GF_Name,Current_BasisFunc.GeomFunc.CPP.Identifier_Name)
Current_BasisFunc.GeomFunc.Opt = GeomFunc.Opt; % set them equal
All_BF(BF_Names{bi}) = Current_BasisFunc;
end
end
end
|
github
|
eardi/sm-fpca-master
|
Write_Sub_DoI_Embedding_Info_in_Setup_Data.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Level_3/@FELDomain/private/Write_Sub_DoI_Embedding_Info_in_Setup_Data.m
| 3,661 |
utf_8
|
77f1ae62fd09cd00790767ad7918969f
|
function status = Write_Sub_DoI_Embedding_Info_in_Setup_Data(obj,fid,Embed)
%Write_Sub_DoI_Embedding_Info_in_Setup_Data
%
% This determines the kind of Subdomain/Domain of Integration (DoI)
% information that is needed to represent the following containment:
% DoI \subset Subdomain \subset Global.
% See also: FELDomain::Get_Sub_DoI_Embedding_Data.
%
% and then it writes that portion of the Setup_Data C++ method to read in this
% information from MATLAB.
% Copyright (c) 06-07-2012, Shawn W. Walker
ENDL = '\n';
TAB = ' ';
% topological dimensions
Global_TD = obj.Global.Top_Dim;
Sub_TD = obj.Subdomain.Top_Dim;
DoI_TD = obj.Integration_Domain.Top_Dim;
fprintf(fid, [TAB, '// check that we have the correct data', ENDL]);
fprintf(fid, [TAB, 'const bool Global_Cell_EMPTY = mxIsEmpty(mxData.mxGlobal_Cell);', ENDL]);
fprintf(fid, [TAB, 'const bool Sub_Cell_EMPTY = mxIsEmpty(mxData.mxSub_Cell);', ENDL]);
fprintf(fid, [TAB, 'const bool Sub_Entity_EMPTY = mxIsEmpty(mxData.mxSub_Entity);', ENDL]);
fprintf(fid, [TAB, 'const bool DoI_Entity_EMPTY = mxIsEmpty(mxData.mxDoI_Entity);', ENDL]);
status = fprintf(fid, ['', ENDL]);
write_error_check_snippet(fid,Embed);
if or(Sub_TD > DoI_TD,Global_TD > Sub_TD)
fprintf(fid, [TAB, '// check the entity indices', ENDL]);
end
if (Sub_TD > DoI_TD)
fprintf(fid, [TAB, 'Error_Check_DoI_Entity_Indices(Data);', ENDL]);
end
if (Global_TD > Sub_TD)
fprintf(fid, [TAB, 'Error_Check_Sub_Entity_Indices(Data);', ENDL]);
end
end
function write_error_check_snippet(fid,Embed)
ENDL = '\n';
TAB = ' ';
TAB2 = [TAB, TAB];
if Embed.Global_Cell_Index
Global_Cell_STR = '(!Global_Cell_EMPTY)'; % not empty
else
Global_Cell_STR = '(Global_Cell_EMPTY)';
end
if Embed.Subdomain_Cell_Index
Sub_Cell_STR = '(!Sub_Cell_EMPTY)'; % not empty
else
Sub_Cell_STR = '(Sub_Cell_EMPTY)';
end
if Embed.Subdomain_Entity_Index
Sub_Entity_STR = '(!Sub_Entity_EMPTY)'; % not empty
else
Sub_Entity_STR = '(Sub_Entity_EMPTY)';
end
if Embed.DoI_Entity_Index
DoI_Entity_STR = '(!DoI_Entity_EMPTY)'; % not empty
else
DoI_Entity_STR = '(DoI_Entity_EMPTY)';
end
fprintf(fid, [TAB, 'if ( (Num_Elem > 0) && ( !(', Global_Cell_STR, ' && ', Sub_Cell_STR,...
' && ', Sub_Entity_STR, ' && ', DoI_Entity_STR, ') ) )', ENDL]);
fprintf(fid, [TAB2, '{', ENDL]);
fprintf(fid, [TAB2, 'mexPrintf("ERROR: ---> There are problems with this Subdomain:\\n");', ENDL]);
fprintf(fid, [TAB2, 'mexPrintf("ERROR: Global Domain: %%s\\n",Global_Name);', ENDL]);
fprintf(fid, [TAB2, 'mexPrintf("ERROR: Subdomain: %%s\\n",Sub_Name);', ENDL]);
fprintf(fid, [TAB2, 'mexPrintf("ERROR: Domain of Integration: %%s\\n",DoI_Name);', ENDL]);
fprintf(fid, [TAB2, 'mexPrintf("ERROR: See Subdomain number %%d.\\n",DOM_INDEX+1);', ENDL]);
fprintf(fid, [TAB2, 'mexPrintf("ERROR: Subdomain data must include the following information:\\n");', ENDL]);
if Embed.Global_Cell_Index
fprintf(fid, [TAB2, 'mexPrintf("ERROR: Global_Cell_Index.\\n");', ENDL]);
end
if Embed.Subdomain_Cell_Index
fprintf(fid, [TAB2, 'mexPrintf("ERROR: Subdomain_Cell_Index.\\n");', ENDL]);
end
if Embed.Subdomain_Entity_Index
fprintf(fid, [TAB2, 'mexPrintf("ERROR: Subdomain_Entity_Index.\\n");', ENDL]);
end
if Embed.DoI_Entity_Index
fprintf(fid, [TAB2, 'mexPrintf("ERROR: DoI_Entity_Index.\\n");', ENDL]);
end
fprintf(fid, [TAB2, 'mexErrMsgTxt("ERROR: Fix your subdomain embedding mesh data!");', ENDL]);
fprintf(fid, [TAB2, '}', ENDL]);
end
|
github
|
eardi/sm-fpca-master
|
Run_Conversion.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Main/@L1toL3/Run_Conversion.m
| 3,268 |
utf_8
|
94a49c4850a727b00187012b4977ede4
|
function [FS, FM, C_Codes, Elems_DoF_Allocation] = Run_Conversion(obj,Main_Dir,Snippet_Dir)
%Run_Conversion
%
% This converts MATS (a Level 1 object) into Level 3 objects.
% Note: there is an intermediate Level 2 object (struct).
% Copyright (c) 11-07-2017, Shawn W. Walker
Domain_of_Integration_Info = obj.Setup_FELDomain;
% create an array of special basis function objects that know nothing about the
% global FE space except for its NAME; just local info (like the reference
% element). This array of objects will be stored within FELSpaces...
FS = obj.Setup_FELSpaces(Domain_of_Integration_Info);
% FELSpace contains one single set of FE spaces and an array of
% Integration_Domains. For each Integration_Domain, a set of basis functions is
% stored that corresponds to the set of FE spaces. In addition, any coefficient
% functions, and extra geometric functions, are also stored in each Integration_Domain.
[FM, Matrix_Parsed] = obj.Init_FELMatrices(FS,Snippet_Dir);
% Note: Matrix_Parsed is a Level 2 object/struct.
[FS, FM] = obj.Define_FELMatrices(FS,FM,Matrix_Parsed);
% remove the parts of the FELSpaces that are not used!
FS = obj.Prune_BasisFunc(FS,FM);
C_Codes = obj.Setup_C_Codes(Main_Dir);
% get collection of Finite Element Definition structs needed for generating
% automatic DoF allocation mex files
Elems_DoF_Allocation = FE_Space_Info_For_DoF_Allocation(obj.MATS);
end
function ELEMS = FE_Space_Info_For_DoF_Allocation(MATS)
ELEMS = containers.Map; % init
Num_Matrix_Data = length(MATS.Matrix_Data);
for ii = 1:Num_Matrix_Data
% get current matrix
MD = MATS.Matrix_Data{ii}(1); % only 1 is needed, b/c space is the same
if ~isempty(MD.Test_Space)
% get the corresponding element
FE_Space_Name = MD.Test_Space.Name;
Elem = MD.Test_Space.Elem;
% only include the FE space if it is *not* a global constant
if ~strcmp(Elem.Transformation,'Constant_Trans')
ELEMS(FE_Space_Name) = Elem;
end
end
if ~isempty(MD.Trial_Space)
% get the corresponding element
FE_Space_Name = MD.Trial_Space.Name;
Elem = MD.Trial_Space.Elem;
% only include the FE space if it is *not* a global constant
if ~strcmp(Elem.Transformation,'Constant_Trans')
ELEMS(FE_Space_Name) = Elem;
end
end
% don't forget to add in any Coef FE spaces
% loop through the integrals
for rr = 1:length(MD.Integral)
Current_Integral = MD.Integral(rr);
if ~isempty(Current_Integral.CoefF)
% loop through all CoefF's
for kk = 1:length(MD.Integral.CoefF)
Specific_CoefF = MD.Integral.CoefF(kk);
% get the corresponding element
FE_Space_Name = Specific_CoefF.Element.Name;
Elem = Specific_CoefF.Element.Elem;
% only include the FE space if it is *not* a global constant
if ~strcmp(Elem.Transformation,'Constant_Trans')
ELEMS(FE_Space_Name) = Elem;
end
end
end
end
end
% add in geometry
ELEMS(MATS.GeoElem.Name) = MATS.GeoElem.Elem;
end
|
github
|
eardi/sm-fpca-master
|
Check_Domains.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Main/@L1toL3/private/Check_Domains.m
| 1,362 |
utf_8
|
ccd50bda6d9cb47d95dda74cbd142496
|
function status = Check_Domains(obj,DS)
%Check_Domains
%
% This just does some basic error checking.
% Copyright (c) 05-25-2012, Shawn W. Walker
status = 0;
% check hold-all domain
if ~isequal(DS.Hold_All,obj.MATS.GeoElem.Domain)
disp('Data structures are inconsistent!');
error('This should not happen. Please report this bug!');
end
Num_Domains = length(DS.Domain_Of_Integration);
for ind = 1:Num_Domains
DoI = DS.Domain_Of_Integration(ind);
if strcmp(DoI.Domain.Name,DoI.Domain.Subset_Of)
disp(['ERROR: Domain of Integration: ', DoI.Domain.Name]);
error('Domain of Integration cannot be a subset of itself!');
end
sbr_check_domain(DoI.Domain,DS.Hold_All);
% check all embeddings domains
for ee=1:length(DoI.Embeddings)
sbr_check_domain(DoI.Embeddings(ee),DS.Hold_All);
end
end
end
function sbr_check_domain(Domain,Hold_All)
% check that the domain is a subset of the Hold_All domain
if ~or(strcmp(Domain.Name,Hold_All.Name),strcmp(Domain.Subset_Of,Hold_All.Name))
disp(['ERROR: problem with this Domain: ', Domain.Name]);
disp(['ERROR: it is not equal to the hold-all domain: ', Hold_All.Name]);
disp(['ERROR: AND it is not a *subset* of the hold-all domain.']);
error('ERROR: check your Domain definitions!');
end
end
|
github
|
eardi/sm-fpca-master
|
Prune_BasisFunc.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Main/@L1toL3/private/Prune_BasisFunc.m
| 2,096 |
utf_8
|
b367a588109f75da7b9d87356575a65c
|
function FS = Prune_BasisFunc(obj,FS,FM)
%Prune_BasisFunc
%
% This removes the basis functions that are not used by the FM object.
% Copyright (c) 06-24-2012, Shawn W. Walker
for ii = 1:length(FS.Integration)
% find the FE spaces that are needed to evaluate contributions to the FE
% matrices on the current integration domain
DoI = FS.Integration(ii).DoI_Geom.Domain.Integration_Domain;
Coef_Funcs = FS.Integration(ii).CoefFunc.values;
Space_Names = get_spaces_for_DoI(Coef_Funcs,FM,DoI);
BF_Set = FS.Integration(ii).BasisFunc.values;
for bi = 1:length(BF_Set)
Current_BF = BF_Set{bi};
% search through matrices to see if it is used
USED = verify_basisfunc_is_used(Space_Names,Current_BF);
% if it is NOT used, then remove it!
if ~USED
remove(FS.Integration(ii).BasisFunc, Current_BF.Space_Name);
end
end
end
end
function Space_Names = get_spaces_for_DoI(Coef_Funcs,FM,DoI)
% get matrices that have a contribution from the current integration domain
FM_Int_Index = FM.Get_Integration_Index(DoI);
Matrix = FM.Integration(FM_Int_Index).Matrix.values;
Map_Names = containers.Map; % init
for mi = 1:length(Matrix)
if ~isempty(Matrix{mi}.row_func.Space_Name)
Map_Names(Matrix{mi}.row_func.Space_Name) = Matrix{mi}.row_func.Space_Name;
end
if ~isempty(Matrix{mi}.col_func.Space_Name)
Map_Names(Matrix{mi}.col_func.Space_Name) = Matrix{mi}.col_func.Space_Name;
end
end
% add in any spaces needed for coefficient functions
for ci = 1:length(Coef_Funcs)
Map_Names(Coef_Funcs{ci}.Space_Name) = Coef_Funcs{ci}.Space_Name;
end
Space_Names = Map_Names.keys; % just need a cell array of names
end
function USED = verify_basisfunc_is_used(Space_Names,BasisFunc)
USED = false; % init
%disp(['Current BasisFunc Space: ', BasisFunc.Space_Name]);
for ind = 1:length(Space_Names)
if strcmp(BasisFunc.Space_Name,Space_Names{ind})
USED = true;
break;
end
end
end
|
github
|
eardi/sm-fpca-master
|
Filter_Domains.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Main/@L1toL3/private/Filter_Domains.m
| 810 |
utf_8
|
5400132f6ad1a34cb8fc92681d483300
|
function DS_Map = Filter_Domains(DS)
%Filter_Domains
%
% This make a container.MAP variable to hold a unique list of domains.
% Copyright (c) 08-01-2011, Shawn W. Walker
Num_DS = length(DS);
DS_Map = containers.Map();
for ind = 1:Num_DS
DS_Map = append_Domain(DS_Map,DS(ind));
end
end
function MAP = append_Domain(MAP,DS)
if ismember(DS.Name,MAP.keys)
% if that domain's name has already been used, then make sure the
% struct (mostly) matches what was used before!
Other_DS = MAP(DS.Name);
if ~strcmp(DS.Type,Other_DS.Type)
% if it doesn't match, then the user was doing things he shouldn't!
disp(['ERROR: This Domain was redefined: ', DS.Name]);
error('You should not redefine a Domain!');
end
end
MAP(DS.Name) = DS;
end
|
github
|
eardi/sm-fpca-master
|
Set_COPY_Struct.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Main/@L1toL3/private/Set_COPY_Struct.m
| 2,270 |
utf_8
|
6437f9ef291a18552bfa051c31c36be0
|
function Integral_SubMAT_Index = Set_COPY_Struct(L2_Obj_Integral,SubMAT_Index)
%Set_COPY_Struct
%
% Do checks to see if the sub-matrix is identical to others. If so, then you
% can just COPY that matrix over.
% Copyright (c) 06-25-2012, Shawn W. Walker
Num_Integral = length(L2_Obj_Integral);
Integral_SubMAT_Index = L2_Obj_Integral(SubMAT_Index); % init
if (Num_Integral==1)
return; % nothing to copy yet...
end
% check all the integrals to see if they are the same as "Integral_SubMAT_Index"
for ind = 1:Num_Integral
if (ind ~= SubMAT_Index) % obviously, ignore the SELF case
[Integral_SubMAT_Index, COPIED] = Set_COPY_Struct_internal(Integral_SubMAT_Index,L2_Obj_Integral(ind),'default');
if ~COPIED
TEMP_L2_Obj_Integral_ind = L2_Obj_Integral(ind);
if and(~isempty(TEMP_L2_Obj_Integral_ind.TestF),~isempty(TEMP_L2_Obj_Integral_ind.TrialF))
% switch test and trial functions
TEMP_L2_Obj_Integral_ind.Arg = Swap_Test_And_Trial_Functions(TEMP_L2_Obj_Integral_ind);
% try to copy again
Integral_SubMAT_Index = Set_COPY_Struct_internal(Integral_SubMAT_Index,TEMP_L2_Obj_Integral_ind,'transpose');
end
end
end
end
end
function [Integral_Out, COPIED] = Set_COPY_Struct_internal(Int_A,Int_B,type)
%Set_COPY_Struct_default
%
% If Integral A and Integral B are the same, then let A copy B;
% recall the routine "Make_Integrand_Use_1st_Tensor_Components"
% Copyright (c) 08-01-2011, Shawn W. Walker
Integral_Out = Int_A; % init
if ~isempty(Integral_Out.COPY)
% this has already been copied!
COPIED = true;
return;
end
% otherwise, see if you can copy!
COPIED = false;
A = Int_A.Arg; % store it
if isempty(Int_B.COPY)
B = Int_B.Arg;
if (A==B)
COPIED = true;
% change the Integral struct
Integral_Out.Original = [];
COPY = Get_L2_Obj_Integral_COPY_Struct();
COPY.Use_SubMAT_Index = Int_B.SubMAT_Index;
COPY.row_index = Int_B.row_index;
COPY.col_index = Int_B.col_index;
COPY.type = type;
Integral_Out.COPY = COPY;
end
end
end
|
github
|
eardi/sm-fpca-master
|
Setup_FELGeoms.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Main/@L1toL3/private/Setup_FELGeoms.m
| 2,852 |
utf_8
|
daff6182d45e825354033321ef8d3495
|
function FS = Setup_FELGeoms(obj,FS)
%Setup_FELGeoms
%
% This inits the GeomFunc Map container under FS.Integration(ind).GeomFunc.
% Copyright (c) 01-23-2014, Shawn W. Walker
Num_Distinct_Integration_Domains = length(FS.Integration);
for ind = 1:Num_Distinct_Integration_Domains
% geometry representation for the domain of integration
DoI_GF = FS.Integration(ind).DoI_Geom;
Current_Integration_Domain = DoI_GF.Domain.Integration_Domain;
% look thru all the matrices
Num_Matrix = length(obj.MATS.Matrix_Data);
for mi = 1:Num_Matrix
ID = obj.MATS.Matrix_Data{mi}.Integral;
% search the integrals!
for kk = 1:length(ID)
% if the integral domain matches the current Integration_Domain
if isequal(ID(kk).Domain,Current_Integration_Domain)
% include any extra geometric functions
for gi = 1:length(ID(kk).GeoF)
% get the domain we are interested in
Extra_Geom_Domain = ID(kk).GeoF(gi).Domain;
% create the object
GF = create_valid_extra_geom_func(DoI_GF,Extra_Geom_Domain);
if ~isempty(GF)
Geom_Domain_Name = GF.Domain.Subdomain.Name;
FS.Integration(ind).GeomFunc(Geom_Domain_Name) = GF; % insert!
end
end
end
end
end
end
% note: don't worry if a GeometricElementFunction gets overwritten; they are
% all on the same domain of integration!
end
function GeomFunc = create_valid_extra_geom_func(DoI_Geom,Extra_Geom_Domain)
%
% This creates a GeometricElementFunction for the domain of integration with
% respect to containment in the domain for which we want geometric information, i.e.
% the Subdomain.
%
% New_Domain.Global = global mesh domain.
% New_Domain.Subdomain = domain corresponding to the geometric data
% that we are interested in.
% New_Domain.Integration_Domain = where to evaluate the geometric data.
%
% Note: DoI_Geom is the geometric function representing the geometry of
% the Global mesh/domain and how the domain of integration is embedded.
% Copyright (c) 01-23-2014, Shawn W. Walker
New_Domain = DoI_Geom.Domain; % init
% set the Subdomain to be the domain where the geometric data is
New_Domain.Subdomain = Extra_Geom_Domain;
Extra_Geom_Domain_TopDim = Extra_Geom_Domain.Top_Dim;
DoI_TopDim = New_Domain.Integration_Domain.Top_Dim;
if (DoI_TopDim > Extra_Geom_Domain_TopDim)
% this is not a valid domain embedding, so return NULL
GeomFunc = [];
else
GeomFunc = GeometricElementFunction(DoI_Geom.Elem,New_Domain);
end
end
|
github
|
eardi/sm-fpca-master
|
Setup_FELSpaces.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Main/@L1toL3/private/Setup_FELSpaces.m
| 2,510 |
utf_8
|
74fb2fe80fa31a9156e117a20a9c1815
|
function FS = Setup_FELSpaces(obj,Domain_Info)
%Setup_FELSpaces
%
% This inits the FELSpaces object.
% Copyright (c) 03-24-2017, Shawn W. Walker
check_geometric_element_domain_geodim_consistency(obj.MATS.GeoElem.Tensor_Comp,Domain_Info);
% create geometric element for the Hold-All container domain
DEBUG = true;
Geom_Elem = ReferenceFiniteElement(obj.MATS.GeoElem.Elem,DEBUG);
% initialize
FS = FELSpaces(Domain_Info,Geom_Elem);
% get unique list of FEM spaces
MAP = containers.Map();
Num_Matrix = length(obj.MATS.Matrix_Data);
for ind = 1:Num_Matrix
FORM = obj.MATS.Matrix_Data{ind};
if ~isa(FORM,'Real')
if ~isempty(FORM.Test_Space)
MAP = Insert_Element_Struct_Into_MAP(FORM.Test_Space,MAP);
end
if ~isempty(FORM.Trial_Space)
MAP = Insert_Element_Struct_Into_MAP(FORM.Trial_Space,MAP);
end
end
% must loop over matrices for the Real case
for ir = 1:size(FORM,1)
for ic = 1:size(FORM,2)
ID = FORM(ir,ic).Integral;
for int_i = 1:length(ID)
for ci = 1:length(ID(int_i).CoefF)
MAP = Insert_Element_Struct_Into_MAP(ID(int_i).CoefF(ci).Element,MAP);
end
end
end
end
end
% append those spaces
FS_cell = MAP.values;
for ind = 1:length(FS_cell)
FS_struct = FS_cell{ind};
REF_ELEM = ReferenceFiniteElement(FS_struct.Elem,DEBUG);
FS = FS.Append_FEM_Space(FS_struct.Domain,FS_struct.Space_Name,REF_ELEM,FS_struct.Tensor_Comp);
end
% include any coefficient functions
FS = obj.Setup_FELCoefs(FS);
% include any extra geoemtric functions
FS = obj.Setup_FELGeoms(FS);
end
function check_geometric_element_domain_geodim_consistency(Tensor_Comp,Domain_Array)
% make sure there is consistency in the geometric dimension
for kk = 1:length(Domain_Array)
Domain_GD = Domain_Array(kk).Integration_Domain.GeoDim;
if (Tensor_Comp~=Domain_GD)
err = FELerror;
err = err.Add_Comment(['The ', 'Geometric', ' Element space does not have the']);
err = err.Add_Comment('same vector dimension as the Domain of Integration.');
err = err.Add_Comment(['Element space has dim = ', num2str(Tensor_Comp)]);
err = err.Add_Comment(['Domain of Integration has dim = ', num2str(Domain_GD)]);
err = err.Add_Comment('Check your Domain definitions!');
err.Error;
error('stop!');
end
end
end
|
github
|
eardi/sm-fpca-master
|
Get_Unique_List_Of_Domains.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Main/@L1toL3/private/Get_Unique_List_Of_Domains.m
| 5,416 |
utf_8
|
cdb1da66abe0e65d346ccdfe773ee67a
|
function SS = Get_Unique_List_Of_Domains(obj)
%Get_Unique_List_Of_Domains
%
% This outputs a structure that looks like:
% SS.Hold_All = Global container domain.
% SS.Domain_Of_Integration(k).
% Domain = integration domain (that is embedded in Hold_All
% domain).
% Embeddings(j) = array of other domains that contain the
% integration domain. These embeddings will
% need to be computed elsewhere (when the
% mesh data is known).
% Copyright (c) 05-25-2012, Shawn W. Walker
% this is THE GLOBAL container set; there should only be one of these no matter
% how many subdomains or domains of integration there are!
SS.Hold_All = obj.MATS.GeoElem.Domain;
% find all domains of integration first
Domains_Of_Integration = containers.Map();
for mi=1:length(obj.MATS.Matrix_Data)
ID = obj.MATS.Matrix_Data{mi}.Integral;
for kk=1:length(ID)
DoI = ID(kk).Domain;
if ismember(DoI.Name,Domains_Of_Integration.keys)
% if that domain was used before, then make sure it did not change!
if ~isequal(DoI,Domains_Of_Integration(DoI.Name))
% if it doesn't match, then the user was doing things he shouldn't!
disp(['ERROR: This Domain was redefined: ', DoI.Name]);
error('You should not redefine a Domain!');
end
else
Domains_Of_Integration(DoI.Name) = DoI;
end
end
end
% % limit to just one domain of integration (for now)
% if length(Domains_Of_Integration) > 1
% error('Can only have one domain of integration.');
% end
List_Of_DoI_Names = Domains_Of_Integration.keys;
% store the Domain of Integration
SS.Domain_Of_Integration = create_domain_of_integration_struct(obj,Domains_Of_Integration(List_Of_DoI_Names{1}));
for ind = 2:length(List_Of_DoI_Names)
% store the Domain of Integration
SS.Domain_Of_Integration(ind) = create_domain_of_integration_struct(obj,Domains_Of_Integration(List_Of_DoI_Names{ind}));
end
% SS
% SS.Domain_Of_Integration(1)
% SS.Domain_Of_Integration(2)
% disp('==========================');
% SS.Domain_Of_Integration(1).Domain
% SS.Domain_Of_Integration(2).Domain
% disp('==========================');
% SS.Domain_Of_Integration(1).Embeddings
% SS.Domain_Of_Integration(2).Embeddings
% safdsafd
end
function DOI = create_domain_of_integration_struct(obj,Single_Domain_Of_Integration)
% this returns a struct:
% DOI.Domain
% DOI.Embeddings(k)
% the DOI.Embeddings(k) is a level 1 Domain that contains the DoI.
%
% So, for every basis function and coefficient function, we need to know that
% the Domain of Integration (DoI) is contained in the domain of definition of
% the function (i.e. we need to know to evaluate the function on a subset (DoI)
% of its domain of definition). This routine records that in the Embeddings
% struct/field. In other words, the Embeddings array contains all domains of
% definition that contain the DoI.
% store the Domain of integration
DOI.Domain = Single_Domain_Of_Integration;
Embed = containers.Map(); % init
for mi=1:length(obj.MATS.Matrix_Data)
ID = obj.MATS.Matrix_Data{mi}.Integral;
for di=1:length(ID)
if isequal(ID(di).Domain,Single_Domain_Of_Integration)
Embed = get_function_domain(Embed, ID(di).TestF, DOI.Domain);
Embed = get_function_domain(Embed, ID(di).TrialF,DOI.Domain);
Embed = get_function_domain(Embed, ID(di).CoefF, DOI.Domain);
end
end
% obj.MATS.Matrix_Data{mi}.TestF
% obj.MATS.Matrix_Data{mi}.TrialF
% obj.MATS.Matrix_Data{mi}.CoefF
%
% Embed = get_function_domain(Embed, obj.MATS.Matrix_Data{mi}.TestF, DOI.Domain);
% Embed = get_function_domain(Embed, obj.MATS.Matrix_Data{mi}.TrialF,DOI.Domain);
% Embed = get_function_domain(Embed, obj.MATS.Matrix_Data{mi}.CoefF, DOI.Domain);
%
% for kk=1:length(ID)
% % find all domains of integration that match...
% if strcmp(ID(kk).Domain.Name,DOI.Domain.Name)
% % ...and store the required embeddings
% for ee=1:length(ID(kk).Embeddings)
% Embed(ID(kk).Embeddings(ee).Name) = ID(kk).Embeddings(ee);
% end
% end
% end
end
% put into the struct
if ~isempty(Embed)
keys = Embed.keys;
DOI.Embeddings = Embed(keys{1});
for kk = 2:length(keys)
DOI.Embeddings(kk) = Embed(keys{kk});
end
else
DOI.Embeddings = []; % no additional embeddings are needed
end
end
function Embed = get_function_domain(Embed, FUNC, DOI_Domain)
for ind = 1:length(FUNC)
% only need to add this functions domain of defn if it is different than the DoI
if ~isequal(FUNC(ind).Element.Domain,DOI_Domain)
% error check: make sure we are only dealing with functions that are
% being *evaluated* on the DOI_Domain
if ~isequal(FUNC(ind).Domain,DOI_Domain)
error('Function (in integrand) must be evaluated on the domain of integration!');
end
% store the domain of defn of the function
Embed(FUNC(ind).Element.Domain.Name) = FUNC(ind).Element.Domain;
end
end
end
|
github
|
eardi/sm-fpca-master
|
FEL_Compute_Exact_Solution_Hessian_Ex_TD_2_GD_3.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Unit_Test/Hessian/TopDim_2_GeoDim_3/FEL_Compute_Exact_Solution_Hessian_Ex_TD_2_GD_3.m
| 2,757 |
utf_8
|
bfb8ed1aaad6355b19396144ae78beb7
|
function Q = FEL_Compute_Exact_Solution_Hessian_Ex_TD_2_GD_3()
%FEL_Compute_Exact_Solution_Hessian_Ex_TD_2_GD_3
%
% Compute exact solution to test FELICITY Auto-Generated Assembly Code.
% Copyright (c) 08-14-2014, Shawn W. Walker
% parameterization of the domain: paraboloid over a unit disk
vr = sym('r','real');
vtheta = sym('theta','real');
vX = [vr .* cos(vtheta); vr .* sin(vtheta); (1 - vr.^2)];
Grad_vX = [diff(vX,'r'), diff(vX,'theta')];
Grad_vX = simplify(Grad_vX);
% compute the metric
g_met = simplify(Grad_vX' * Grad_vX);
g_met_inv = simplify(inv(g_met));
% define function
f1 = (vr.*cos(vtheta)).^2 .* (vr.*sin(vtheta)).^2;
%f1 = (vr.^1).*sin(vtheta).*exp(-vr);
f1
% compute the surface gradient and hessian (in local coordinates)
surf_grad_f1 = surf_grad(f1,g_met_inv,Grad_vX);
% compute the COVARIANT surface hessian!
% compute derivatives of soln (in reference domain)
func_grad = [diff(f1,'r',1); diff(f1,'theta',1)];
% compute hessian of soln (in reference domain)
func_hess = [diff(f1,'r','r'), diff(f1,'r','theta');
diff(f1,'theta','r'), diff(f1,'theta','theta')];
%
% differentiate metric
grad_metric(2).mat = [];
grad_metric(1).mat = simplify(diff(g_met,'r'));
grad_metric(2).mat = simplify(diff(g_met,'theta'));
% compute the Christoffel symbols (2nd kind)
Gamma(2).ij = sym(zeros(2,2));
for kk=1:2
for ii=1:2
for jj=1:2
TEMP = sym(0);
for ll=1:2
TEMP = TEMP + g_met_inv(kk,ll) * ( grad_metric(ii).mat(ll,jj) + grad_metric(jj).mat(ii,ll) - grad_metric(ll).mat(ii,jj) );
end
Gamma(kk).ij(ii,jj) = (1/2) * simplify(TEMP);
end
end
end
% compute "local" term
local_hess = func_hess - ( func_grad(1) * Gamma(1).ij + func_grad(2) * Gamma(2).ij );
local_hess = simplify(local_hess);
% map to surface
J_g_inv_MAT = Grad_vX * g_met_inv;
surf_hess_f1 = J_g_inv_MAT * local_hess * (transpose(J_g_inv_MAT));
%old incorrect way
%surf_hess_f1 = surf_grad(surf_grad_f1',g_met_inv,Grad_vX);
% compute Frob norm squared of hessian
%f1_Norm_Sq = simplify(sum(sum(surf_hess_f1.^2)));
%f1_Norm_Sq
%hess_11 = simplify(surf_hess_f1(1,1));
hess_trace = simplify(trace(surf_hess_f1));
% compute integrand of L^2 norm squared of hessian of f
%integrand = simplify(f1_Norm_Sq * sqrt(det(g_met)));
integrand = simplify(hess_trace * sqrt(det(g_met)));
%integrand
integrand_FH = matlabFunction(integrand);
%integrand_FH
XMIN = 0;
XMAX = 1;
YMIN = 0;
YMAX = 2*pi;
Q = integral2(integrand_FH,XMIN,XMAX,YMIN,YMAX,'AbsTol',1e-15);
end
function grad_func = surf_grad(func,g_met_inv,Grad_vX)
local_grad_func = [diff(func,'r'), diff(func,'theta')];
grad_func = simplify(local_grad_func * g_met_inv * Grad_vX');
end
|
github
|
eardi/sm-fpca-master
|
FEL_Execute_Bending_Plate_2D.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Unit_Test/Mixed_HHJ/Bending_Plate_2D/FEL_Execute_Bending_Plate_2D.m
| 41,909 |
utf_8
|
4b183a62ac0dfcc71c95b66ffa40616c
|
function status = FEL_Execute_Bending_Plate_2D(deg_geo,deg_k,omega,exact_u,exact_u_hess,...
Mesh_type,BC_type)
%FEL_Execute_Bending_Plate_2D
%
% test FELICITY Auto-Generated Assembly Code
% Copyright (c) 03-29-2018, Shawn W. Walker
Main_Dir = fileparts(mfilename('fullpath'));
PD = [];
if strcmpi(Mesh_type,'square')
Refine_Vec = [0 1 2 3 4 5 6 7]; % went to 9...
elseif strcmpi(Mesh_type,'pacman')
Refine_Vec = [0 1 2 3 4 5 6]; % <= 6
elseif strcmpi(Mesh_type,'refined_disk')
Refine_Vec = [0 1 2 3 4 5 6 7]; % <= 9
elseif strcmpi(Mesh_type,'refined_disk_alt')
Refine_Vec = [0 1 2 3 4 5];% 7 8]; % <= 9
elseif strcmpi(Mesh_type,'disk_n_gon')
Refine_Vec = [1 2 3 4]; % <= 6
elseif strcmpi(Mesh_type,'circle_alt')
NumR = 7;
Refine_Vec = (0:1:NumR)';
Mesh_Name = 'Circle_Mesh';
HHJ_Mesh_Dir = 'C:\FILES\FEM_Code\HHJ_Meshes\';
[MR, PD] = Generate_Refined_HHJ_Meshes(Mesh_Name,HHJ_Mesh_Dir,NumR);
else
error('Invalid!');
end
Num_Refine = length(Refine_Vec);
% init arrays for storing numerical errors
Error_Info.u_L_inf = zeros(Num_Refine,1);
Error_Info.u_L2 = zeros(Num_Refine,1);
Error_Info.u_H1_semi = zeros(Num_Refine,1);
Error_Info.u_H2_semi = zeros(Num_Refine,1);
Error_Info.sig_L2 = zeros(Num_Refine,1);
Error_Info.sig_Gamma_L2 = zeros(Num_Refine,1);
Error_Info.sig_Skel_L2 = zeros(Num_Refine,1);
Error_Info.normal_L2 = zeros(Num_Refine,1);
% store u values at origin
u_origin = zeros(Num_Refine,1);
% % store the solution
% Soln_Level(Num_Refine).u = [];
% Soln_Level(Num_Refine).sig = [];
% create struct to hold output of simulation
Sim_Info.sides = zeros(Num_Refine,1);
Sim_Info.elems = zeros(Num_Refine,1);
Sim_Info.dofs = zeros(Num_Refine,1);
for kk = 1:Num_Refine
% BEGIN: define reference mesh
Refine_Level = Refine_Vec(kk);
disp('==============================================');
disp(['Run refinement level: ', num2str(Refine_Level)]);
MM = [];
if strcmpi(Mesh_type,'square')
% get mesh of [0, 1] x [0, 1]
X_Len = 1;
Y_Len = 1;
NX = X_Len * 2^Refine_Level + 1;
NY = Y_Len * 2^Refine_Level + 1;
[Tri, Pts] = regular_triangle_mesh(NX, NY);
Pts(:,1) = X_Len * Pts(:,1);
Pts(:,2) = Y_Len * Pts(:,2);
elseif strcmpi(Mesh_type,'pacman')
% % create a pac-man mesh
% [Tri, Pts] = triangle_mesh_of_disk([0, 0],1,Refine_Level);
% MT = MeshTriangle(Tri, Pts, 'Omega');
%
% % remove a section
% CC = MT.Get_Cell_Centers();
% ANG1 = atan2d(CC(:,2),CC(:,1));
% Mask_Keep = (ANG1 < 135) & (ANG1 > -135);
% Tri = Tri(Mask_Keep,:);
% MT = MeshTriangle(Tri, Pts, 'Omega');
% MT = MT.Remove_Unused_Vertices();
%
% Tri = MT.ConnectivityList;
% Pts = MT.Points;
% clear MT;
% load up a mesh
FN = ['C:\FILES\FELICITY\Demo\CiarletRaviart\ZZ_Pacman_Meshes\pacman_', num2str(Refine_Level), '.mat'];
DD = load(FN);
Tri = DD.Tri;
Pts = DD.Pts;
clear DD;
% now scale the angle
R = sqrt(sum(Pts.^2,2));
THETA = atan2(Pts(:,2),Pts(:,1));
ORIGIN = (R < 1e-14);
Ref_omega = 3*pi/2;
New_omega = omega;
THETA = (New_omega/Ref_omega) * THETA;
XX = R .* cos(THETA);
YY = R .* sin(THETA);
Pts = [XX, YY];
Pts(ORIGIN,:) = [0, 0];
clear R THETA XX YY;
elseif strcmpi(Mesh_type,'refined_disk')
% create a disk mesh
[Tri, Pts] = triangle_mesh_of_disk([0, 0],1,Refine_Level);
% % create mesher object
% Box_Dim = [-1.2, 1.2];
% Num_BCC_Points = 2^Refine_Level + 4;
% Use_Newton = true;
% TOL = 1E-12; % tolerance to use in computing the cut points
% % BCC mesh of the unit square [0,1] x [0,1]
% MG = Mesher2Dmex(Box_Dim,Num_BCC_Points,Use_Newton,TOL);
%
% LS = LS_Disk();
% LS.Param.rad = [1.0];
% LS.Param.cx = [0];
% LS.Param.cy = [0];
%
% Interp_Handle = @(pt) LS.Interpolate(pt);
%
% MG = MG.Get_Cut_Info(Interp_Handle);
% [Tri, Pts] = MG.run_mex(Interp_Handle);
elseif strcmpi(Mesh_type,'refined_disk_alt')
% create a disk mesh
[Tri, Pts] = bcc_triangle_mesh(2,2);
for rr = 1:Refine_Level
Marked = (1:1:size(Tri,1))';
[Pts, Tri] = Refine_Entire_Mesh(Pts,Tri,[],Marked);
end
% shift it
Pts(:,1) = Pts(:,1) - 0.5;
Pts(:,2) = Pts(:,2) - 0.5;
% scale it!
Pts = ((1/sqrt(2))/0.5) * Pts;
elseif strcmpi(Mesh_type,'disk_n_gon')
% load up a mesh
Num_Sides_Vec = [8 16 32 64 136 264];
NS = Num_Sides_Vec(Refine_Level);
FN = ['C:\FILES\FELICITY\Code_Generation\Matrix_Assembly\Unit_Test\Hdivdiv\Bending_Plate_2D\disk_n_gon_', num2str(NS), '.mat'];
DD = load(FN);
Tri = DD.Tri;
Pts = DD.Pts;
clear DD;
elseif strcmpi(Mesh_type,'circle_alt')
% load up a mesh
MM = MR(kk);
Tri = MM.TRI;
Pts = MM.VTX;
%MR(kk+1).TRI, MR(kk+1).VTX, MR(kk+1).BdyEDGE, MR(kk+1).BdyChart_Ind, MR(kk+1).BdyChart_Var, MR(kk+1).BdyTRI_Ind
else
error('Invalid!');
end
% disk of radius 0.5
% Pts = 1*[0, 0; 1, 0; 0, 1];
% Tri = [1 2 3];
% Pts = 1*[0, 0; 1, 0; 0.5, 1];
% Tri = [1 2 3];
% Pts = [0, 0; 1, 0; 1, 1; 0, 1];
% Tri = [1 2 3; 1 3 4];
% Pts = [0, 0; 1, 0; 1, 1; 0, 1; 0.3, 0.4];
% Tri = [1 2 5; 2 3 5; 3 4 5; 4 1 5];
% Pts = [0, 0; 1, 0; 0, 1; 1, 1];
% Tri = [1 2 3; 2 4 3];
%Pts = [Pts, 0*Pts(:,1)];
Mesh = MeshTriangle(Tri, Pts, 'Omega');
clear Tri Pts;
% END: define reference mesh
% add the boundary
if isempty(MM)
Mesh = Mesh.Remove_Unused_Vertices();
Mesh = Mesh.Reorder();
BDY = Mesh.freeBoundary();
Mesh = Mesh.Append_Subdomain('1D','Gamma',BDY);
else
Mesh = Mesh.Append_Subdomain('1D','Gamma',MM.BdyEDGE);
end
% add the skeleton
Mesh = Mesh.Append_Skeleton('Skeleton_Plus','Skeleton_Minus');
% % plot mesh
% figure;
% Mesh.Plot;
% hold on;
% Mesh.Plot_Subdomain('Gamma');
% hold off;
% % plot mesh
% figure;
% % Mesh.Plot;
% hold on;
% Mesh.Plot_Subdomain('Skeleton_Plus');
% %Mesh.Plot_Subdomain('Skeleton_Minus');
% hold off;
% axis equal;
if (kk==Num_Refine)
% plot the exact solution
exact_u_func = matlabFunction(exact_u);
%exact_u_func
xp = Mesh.Points(:,1);
yp = Mesh.Points(:,2);
exact_u_interp = exact_u_func(xp,yp);
figure;
trisurf(Mesh.ConnectivityList,xp,yp,exact_u_interp);
shading interp;
AX = Mesh.Bounding_Box;
AX = AX(1:4);
view(2);
axis(AX);
axis equal;
axis(AX);
title('True Exact Solution');
colorbar;
%safdsadf
end
% compute embedding data
Domain_Names = {'Omega'; 'Gamma'; 'Skeleton_Plus'; 'Skeleton_Minus'};
Omega_Subdomains = Mesh.Generate_Subdomain_Embedding_Data(Domain_Names);
[G_Space, Geo_Points, Geo_Points_hat, V_Space, W_Space, SkDG_Space, OmegaDG_Space] =...
create_FE_spaces(Main_Dir,Mesh,deg_geo,deg_k,Mesh_type,BC_type,PD,MM);
%
% % update P1 mesh with deformed coordinates
% DM_13 = W_Space.DoFmap(:,1:3);
% P1_pts = 0*Mesh.Points; % init
% TRI = Mesh.ConnectivityList;
% P1_pts(TRI(:),:) = Geo_Points(DM_13(:),:);
% Mesh = Mesh.Set_Points(P1_pts);
% disp('Points:');
% Mesh.Points
%
% disp('Triangulation:');
% uint32(Mesh.ConnectivityList)
%
% disp('V_Space DoFmap:');
% V_Space.DoFmap
% evaluate exact functions
exact_u_func = matlabFunction(exact_u);
W_X = W_Space.Get_DoF_Coord(Mesh,G_Space,Geo_Points);
I_u_exact = exact_u_func(W_X(:,1),W_X(:,2));
exact_u_hess_11 = matlabFunction(exact_u_hess(1,1));
exact_u_hess_12 = matlabFunction(exact_u_hess(1,2));
exact_u_hess_21 = matlabFunction(exact_u_hess(2,1));
exact_u_hess_22 = matlabFunction(exact_u_hess(2,2));
% exact_u_hess_11
% exact_u_hess_12
% exact_u_hess_21
% exact_u_hess_22
eps1 = 1e-20; % to avoid 0/0
sig_exact_W_X = [exact_u_hess_11(W_X(:,1) + eps1,W_X(:,2) + eps1), exact_u_hess_12(W_X(:,1) + eps1,W_X(:,2) + eps1),...
exact_u_hess_21(W_X(:,1) + eps1,W_X(:,2) + eps1), exact_u_hess_22(W_X(:,1) + eps1,W_X(:,2) + eps1)];
%
% I_sig_exact_11 = sig_exact_W_X(:,1);
% I_sig_exact_12 = sig_exact_W_X(:,2);
% I_sig_exact_22 = sig_exact_W_X(:,4);
% I_sig_exact_11
% I_sig_exact_12
% I_sig_exact_22
sig_soln = V_Space.Get_Zero_Function;
u_soln = W_Space.Get_Zero_Function;
% assemble
tic
FEM = UNIT_TEST_mex_Assemble_Bending_Plate_2D([],Geo_Points,G_Space.DoFmap,[],Omega_Subdomains,...
V_Space.DoFmap,W_Space.DoFmap,sig_soln,u_soln);
toc
tic
FEM_hat = UNIT_TEST_mex_Assemble_Bending_Plate_2D([],Geo_Points_hat,G_Space.DoFmap,[],Omega_Subdomains,...
V_Space.DoFmap,W_Space.DoFmap,sig_soln,u_soln);
toc
% put FEM into a nice object to make accessing the matrices easier
my_Mats = FEMatrixAccessor('Bending Plate',FEM);
my_Mats_hat = FEMatrixAccessor('Bending Plate',FEM_hat);
clear FEM;
% pull out the matrices
M = my_Mats.Get_Matrix('Mass_Matrix');
M_hat = my_Mats_hat.Get_Matrix('Mass_Matrix');
M_Scalar = my_Mats.Get_Matrix('Mass_Matrix_Scalar');
Jump_Term = my_Mats.Get_Matrix('Jump_Term');
Jump_Term_hat = my_Mats_hat.Get_Matrix('Jump_Term');
Grad_Grad_Term = my_Mats.Get_Matrix('Grad_Grad_Term');
Grad_Grad_Term_hat = my_Mats_hat.Get_Matrix('Grad_Grad_Term');
DivDiv_h_Term = Grad_Grad_Term - Jump_Term;
DivDiv_h_Term_hat = Grad_Grad_Term_hat - Jump_Term_hat;
RHS_F = my_Mats.Get_Matrix('RHS_F');
RHS_F_hat = my_Mats_hat.Get_Matrix('RHS_F');
RHS_B = my_Mats.Get_Matrix('RHS_B');
u_H1_Norm = sqrt(my_Mats.Get_Matrix('u_H1_Error_Sq'));
sig_L2_Norm = sqrt(my_Mats.Get_Matrix('sig_L2_Error_Sq'));
u_H1_Norm
sig_L2_Norm
% disp('Mass Matrix:');
% full(M)
%
% disp('Grad_Grad_Term:');
% full(Grad_Grad_Term)
%
% disp('Jump_Term:');
% full(Jump_Term)
% disp('Compute difference of DivDiv_h_Term and DivDiv_h_Term_hat:');
% DivDiv_h_ERR = abs(DivDiv_h_Term - DivDiv_h_Term_hat);
% TEMP = DivDiv_h_ERR * inv(M_hat) * (DivDiv_h_ERR');
% %max(DivDiv_h_ERR(:))
% norm(full(TEMP),2)
% figure;
% imagesc(DivDiv_h_ERR);
% colorbar;
% axis equal;
% % define f
% exact_f = @(x,y) 0*x - 0.1;
% % evaluate given smooth function
% G_Space = G_Space.Set_mex_Dir(Main_Dir,'UNIT_TEST_mex_Interp_G_Space_Bending_Plate_2D');
% W_X = W_Space.Get_DoF_Coord(Mesh,G_Space,Geo_Points);
% f_h = exact_f(W_X(:,1),W_X(:,2));
% solve problem
Num_V_DoF = V_Space.num_dof;
Num_W_DoF = W_Space.num_dof;
MAT = [M, -DivDiv_h_Term';
-DivDiv_h_Term, sparse(Num_W_DoF,Num_W_DoF)];
%
RHS = [zeros(Num_V_DoF,1); - RHS_F - RHS_B];
BDY = Mesh.Get_Global_Subdomain('Gamma');
Sim_Info.sides(kk) = size(BDY,1);
Sim_Info.elems(kk) = Mesh.Num_Cell();
Sim_Info.dofs(kk) = length(RHS);
Fixed_V_DoFs = V_Space.Get_Fixed_DoFs(Mesh);
Free_V_DoFs = V_Space.Get_Free_DoFs(Mesh);
Free_W_DoFs = W_Space.Get_Free_DoFs(Mesh);
% find the fixed DoFs a different way
% Mesh.Subdomain(1).Data
%
% V_Space.RefElem.Nodal_Top.V
%
% V_Space.RefElem.Nodal_Top.E{1}(Mesh.Subdomain(1).Data,:)
%
% V_Space.RefElem.Nodal_Top.F
%
% V_Space.RefElem.Nodal_Top.T
% Local_Edge_DoFs = V_Space.RefElem.Nodal_Top.E{1}(Mesh.Subdomain(1).Data(:,2),:);
%
% SubDoFmap = V_Space.DoFmap(Mesh.Subdomain(1).Data(:,1),:);
%
% LI = (1:1:size(Local_Edge_DoFs,1))';
% % Local_Edge_DoFs_1 = [LI, Local_Edge_DoFs(:,1)];
% % Local_Edge_DoFs_2 = [LI, Local_Edge_DoFs(:,2)];
% % Local_Edge_DoFs_3 = [LI, Local_Edge_DoFs(:,3)];
%
% % Local_Edge_DoFs_1
% % Local_Edge_DoFs_2
% % Local_Edge_DoFs_3
%
% IND_1 = sub2ind(size(SubDoFmap),LI,Local_Edge_DoFs(:,1));
% IND_2 = sub2ind(size(SubDoFmap),LI,Local_Edge_DoFs(:,2));
% IND_3 = sub2ind(size(SubDoFmap),LI,Local_Edge_DoFs(:,3));
%
% DoF_1 = SubDoFmap(IND_1);
% DoF_2 = SubDoFmap(IND_2);
% DoF_3 = SubDoFmap(IND_3);
%
% Fixed_V_DoFs_ALT = [DoF_1; DoF_2; DoF_3];
%
% Fixed_V_DoFs_ALT = unique(Fixed_V_DoFs_ALT);
%
% disp('DoF Difference:');
% max(abs(Fixed_V_DoFs - Fixed_V_DoFs_ALT))
% [LIA, LOCB] = ismember(Fixed_V_DoFs,double(V_Space.DoFmap(:,1:9)));
% LIA
% disp('BB:');
% BB = DivDiv_h_Term(Free_W_DoFs,Free_V_DoFs);
% size(BB)
% S = svd(full(BB), 'econ');
% length(S)
% disp('Ratio:');
% S(1)/S(end)
if or(strcmpi(BC_type,'free'),strcmpi(BC_type,'alternate'))
% need to get mean value zero part of displacement
[~, ind_1] = min(W_X(:,1) + W_X(:,2));
[~, ind_2] = max(W_X(:,1) + W_X(:,2));
[~, ind_3] = min(W_X(:,1) - W_X(:,2));
Fixed_W_DoFs = [ind_1, ind_2, ind_3]';
Free_W_DoFs = setdiff(Free_W_DoFs,Fixed_W_DoFs); % remove three more DoFs
Free_DoFs = [Free_V_DoFs; Free_W_DoFs + Num_V_DoF];
% i.e. just remove one DoF for now, which means we are setting the
% displacement to zero there
else
Free_DoFs = [Free_V_DoFs; Free_W_DoFs + Num_V_DoF];
end
Soln = zeros(Num_V_DoF + Num_W_DoF,1);
% add in BCs
disp('Add in stress boundary conditions:');
Proj_hess = my_Mats.Get_Matrix('Proj_sig');
%L2_Proj_hess = 0*sig_soln;
L2_Proj_hess = M \ Proj_hess;
L2_Proj_hess(Free_V_DoFs,1) = 0;
displace_val = zeros(Num_W_DoF,1);
displace_val(Fixed_W_DoFs,1) = I_u_exact(Fixed_W_DoFs,1);
Soln_BC = [L2_Proj_hess; displace_val];
RHS = RHS - MAT*Soln_BC;
disp('Solve mixed HHJ system:');
tic
Soln(Free_DoFs) = MAT(Free_DoFs,Free_DoFs) \ RHS(Free_DoFs,1);
toc
sig_soln = Soln(1:Num_V_DoF,1);
u_soln = Soln(Num_V_DoF+1:Num_V_DoF+Num_W_DoF,1);
disp('Set solution at points:');
u_soln(Fixed_W_DoFs,1) = displace_val(Fixed_W_DoFs,1);
u_soln(Fixed_W_DoFs,1)
% disp('Compute "discrete" norms:');
% DivDiv_h_ERR = DivDiv_h_Term - DivDiv_h_Term_hat;
% TEMP = M_hat(Free_V_DoFs,Free_V_DoFs) \ (DivDiv_h_ERR(:,Free_V_DoFs)') * u_soln;
% u_norm = sqrt(abs(u_soln' * DivDiv_h_ERR(:,Free_V_DoFs) * TEMP));
% u_norm
disp('Check \sigma DoFs on \Gamma:');
max(abs(sig_soln(Fixed_V_DoFs)))
if or(strcmpi(BC_type,'free'),strcmpi(BC_type,'alternate'))
% need to get mean value zero part of displacement
% compute average value
Area_Domain = full(sum(M_Scalar(:)));
Ave_u_value = sum(M_Scalar * u_soln) / Area_Domain;
% % subtract off
% u_soln = u_soln - Ave_u_value;
% % SWW: this can cause an issue for computing the L2 norm of the error,
% % because the exact solution may differ by a constant.
end
% compute the HHJ interpolant of the exact hessian
if (deg_k==0)
FEM = UNIT_TEST_mex_Assemble_HHJ_Interp_2D([],Geo_Points,G_Space.DoFmap,[],Omega_Subdomains,...
SkDG_Space.DoFmap,V_Space.DoFmap);
else
FEM = UNIT_TEST_mex_Assemble_HHJ_Interp_2D([],Geo_Points,G_Space.DoFmap,[],Omega_Subdomains,...
OmegaDG_Space.DoFmap,SkDG_Space.DoFmap,V_Space.DoFmap);
end
% put FEM into a nice object to make accessing the matrices easier
HHJ_Interp_Mats = FEMatrixAccessor('HHJ Interp',FEM);
clear FEM;
% pull out the matrices
NN_DoF = HHJ_Interp_Mats.Get_Matrix('NN_DoF');
NN_RHS = HHJ_Interp_Mats.Get_Matrix('NN_RHS');
% compute the interpolant
if (deg_k==0)
%Free_SkDG_DoFs = SkDG_Space.Get_Free_DoFs(Mesh);
%HHJ_Interp_sig = V_Space.Get_Zero_Function();
%HHJ_Interp_sig(Free_V_DoFs,1) = NN_DoF(Free_SkDG_DoFs,Free_V_DoFs) \ NN_RHS(Free_V_DoFs,1);
HHJ_Interp_sig = NN_DoF \ NN_RHS;
HHJ_Interp_sig(Fixed_V_DoFs,1) = 0; % set boundary values to zero
else
Internal_DoF_11 = HHJ_Interp_Mats.Get_Matrix('Internal_DoF_11');
Internal_DoF_12 = HHJ_Interp_Mats.Get_Matrix('Internal_DoF_12');
Internal_DoF_22 = HHJ_Interp_Mats.Get_Matrix('Internal_DoF_22');
Internal_RHS_11 = HHJ_Interp_Mats.Get_Matrix('Internal_RHS_11');
Internal_RHS_12 = HHJ_Interp_Mats.Get_Matrix('Internal_RHS_12');
Internal_RHS_22 = HHJ_Interp_Mats.Get_Matrix('Internal_RHS_22');
HHJ_MAT = [NN_DoF; Internal_DoF_11; Internal_DoF_12; Internal_DoF_22];
HHJ_RHS = [NN_RHS; Internal_RHS_11; Internal_RHS_12; Internal_RHS_22];
HHJ_Interp_sig = HHJ_MAT \ HHJ_RHS;
HHJ_Interp_sig(Fixed_V_DoFs,1) = 0; % set boundary values to zero
end
%sig_soln = HHJ_Interp_sig;
% % store the solution
% Soln_Level(kk).sig = sig_soln;
% Soln_Level(kk).u = u_soln;
% % load the solution info
% SL_Data = load(fullfile(Main_Dir, 'Soln_Data.mat'));
% Soln_Level = SL_Data.Soln_Level;
% clear SL_Data;
% % sig_soln = Soln_Level(kk).sig;
% % u_soln = Soln_Level(kk).u;
tic
FEM = UNIT_TEST_mex_Assemble_Bending_Plate_2D([],Geo_Points,G_Space.DoFmap,[],Omega_Subdomains,...
V_Space.DoFmap,W_Space.DoFmap,sig_soln,u_soln);
toc
% put FEM into a nice object to make accessing the matrices easier
my_Mats = FEMatrixAccessor('Bending Plate',FEM);
clear FEM;
% Proj_hess = my_Mats.Get_Matrix('Proj_sig');
% L2_Proj_hess = 0*sig_soln;
%
% RR = (DivDiv_h_Term') * u_soln;
% %L2_Proj_hess(Free_V_DoFs,1) = M(Free_V_DoFs,Free_V_DoFs) \ Proj_hess(Free_V_DoFs,1);
% L2_Proj_hess(Free_V_DoFs,1) = M(Free_V_DoFs,Free_V_DoFs) \ RR(Free_V_DoFs,1);
% %L2_Proj_hess = M \ RR;
% sig_soln = L2_Proj_hess;
%
% % Discrete_Diff = L2_Proj_hess - sig_soln;
% % Discrete_L2_Error = sqrt(Discrete_Diff' * M * Discrete_Diff);
% % Discrete_L2_Error
% tic
% FEM = UNIT_TEST_mex_Assemble_Bending_Plate_2D([],Geo_Points,G_Space.DoFmap,[],Omega_Subdomains,...
% V_Space.DoFmap,W_Space.DoFmap,L2_Proj_hess,u_soln);
% toc
% % put FEM into a nice object to make accessing the matrices easier
% my_Mats = FEMatrixAccessor('Bending Plate',FEM);
% clear FEM;
%disp('nn_Gamma:');
%nn_Gamma = my_Mats.Get_Matrix('nn_Gamma');
nn_Gamma_Mass_Matrix = my_Mats.Get_Matrix('nn_Gamma_Mass_Matrix');
sig_soln_test = sig_soln;
%sig_soln_test(Fixed_V_DoFs,1) = 0;
nn_Gamma_sig_test_L2_norm = sqrt(sig_soln_test' * nn_Gamma_Mass_Matrix * sig_soln_test);
nn_Gamma_sig_test_L2_norm
u_L2_Error_Sq = my_Mats.Get_Matrix('u_L2_Error_Sq');
Error_Info.u_L2(kk) = sqrt(u_L2_Error_Sq);
u_H1_Error_Sq = my_Mats.Get_Matrix('u_H1_Error_Sq');
Error_Info.u_H1_semi(kk) = sqrt(u_H1_Error_Sq);
u_H2_Error_Sq = my_Mats.Get_Matrix('u_H2_Error_Sq');
Error_Info.u_H2_semi(kk) = sqrt(u_H2_Error_Sq);
sig_L2_Error_Sq = my_Mats.Get_Matrix('sig_L2_Error_Sq');
Error_Info.sig_L2(kk) = sqrt(sig_L2_Error_Sq);
% % overwrite!
% sig_other = Soln_Level(kk).sig;
% sig_diff = (sig_soln - sig_other);
% Error_Info.sig_L2(kk) = sqrt(abs(sig_diff' * M * sig_diff));
sig_Gamma_L2_Error_Sq = my_Mats.Get_Matrix('sig_Gamma_L2_Error_Sq');
Error_Info.sig_Gamma_L2(kk) = sqrt(sig_Gamma_L2_Error_Sq);
sig_Skel_L2_Error_Sq = my_Mats.Get_Matrix('sig_Skel_L2_Error_Sq');
Error_Info.sig_Skel_L2(kk) = sqrt(sig_Skel_L2_Error_Sq);
normal_L2_error_Sq = my_Mats.Get_Matrix('normal_L2_error_Sq');
Error_Info.normal_L2(kk) = sqrt(normal_L2_error_Sq);
Error_Info.u_L_inf(kk) = max(abs(u_soln - I_u_exact));
% get value at origin
Origin_ind = sqrt(sum(W_X.^2,2)) < 1e-13;
u_origin(kk) = u_soln(Origin_ind,1);
% store number of triangles
Sim_Info.elems(kk) = Mesh.Num_Cell();
% find points in mesh
Cell_Indices = uint32([1; 2]);
% set some random global points
Omega_Neighbors = uint32(Mesh.neighbors);
Omega_Given_Points = {Cell_Indices, [0.234, 0.112; 0.114, 0.009], Omega_Neighbors};
% % find points in mesh
% Cell_Indices = uint32(ones(size(W_X,1),1));
% % set some random global points
% Omega_Neighbors = uint32(Mesh.neighbors);
% Omega_Given_Points = {Cell_Indices, W_X, Omega_Neighbors};
% hold on;
% plot(W_X(:,1),W_X(:,2),'bd');
% hold off;
% Vtx = Geo_Points;
% Tri = double(G_Space.DoFmap);
% search!
tic
SEARCH = UNIT_TEST_mex_FEL_Pt_Search_Bending_Plate_2D(Geo_Points(:,1:2),G_Space.DoFmap,[],[],Omega_Given_Points);
toc
SEARCH.DATA{1}
SEARCH.DATA{2}
% skip the search, you know how they are embedded...
CI = zeros(size(W_X,1),1);
RefCoord = zeros(size(W_X,1),2);
Local_RefCoord = W_Space.RefElem.Nodal_Data.BC_Coord(:,2:3);
DM = double(W_Space.DoFmap);
for di = 1:size(Local_RefCoord,1)
RefCoord(DM(:,di),1) = Local_RefCoord(di,1);
RefCoord(DM(:,di),2) = Local_RefCoord(di,2);
CI(DM(:,di),1) = (1:1:size(DM,1))';
end
SEARCH.DATA = {uint32(CI), RefCoord};
% now interpolate
Omega_Interp_Data = SEARCH.DATA;
% Omega_Interp_Pts = Mesh.referenceToCartesian(double(Omega_Interp_Data{1}), Omega_Interp_Data{2});
% Omega_Interp_Pts
INTERP = UNIT_TEST_mex_FEL_Interp_Bending_Plate_2D(Geo_Points(:,1:2),G_Space.DoFmap,[],[],Omega_Interp_Data,V_Space.DoFmap,sig_soln);
% extract data
%INTERP.DATA
% sig_hess_1 = [INTERP.DATA{1,1}(1), INTERP.DATA{1,2}(1);
% INTERP.DATA{2,1}(1), INTERP.DATA{2,2}(1)];
% sig_hess_2 = [INTERP.DATA{1,1}(2), INTERP.DATA{1,2}(2);
% INTERP.DATA{2,1}(2), INTERP.DATA{2,2}(2)];
% %
% sig_hess_1
% sig_hess_2
sig_soln_W_X = [INTERP(1).DATA{1,1}, INTERP(1).DATA{1,2}, INTERP(1).DATA{2,1}, INTERP(1).DATA{2,2}];
sig_error_W_X = -(sig_exact_W_X - sig_soln_W_X);
sig_abs_error_W_X = sum(abs(sig_error_W_X),2);
end
% % save the solution info
% save(fullfile(Main_Dir, 'Soln_Data.mat'),'Soln_Level');
TXT_DUMP_FN = ['HHJ_Conv_', Mesh_type, '_', BC_type,...
'_degGEO_', num2str(deg_geo), '_degHHJ_', num2str(deg_k), '.txt'];
text_FN = fullfile(Main_Dir, TXT_DUMP_FN);
delete(text_FN);
diary(text_FN);
disp(' ');
disp(' ');
disp([' Mesh Type: ', Mesh_type]);
disp(['Boundary Condition Type: ', BC_type]);
disp(' ');
disp(['Degree of Geometry: ', num2str(deg_geo)]);
disp(['Degree of HHJ: ', num2str(deg_k)]);
disp(' ');
% disp('Number of triangles = N_T');
% disp(' ');
disp('Error Stats for w in L^2(\Omega) and H^1(\Omega):');
disp(' ');
display_error_stats(Sim_Info,'w, L^2(O)',Error_Info.u_L2,'w, H^1(O)',Error_Info.u_H1_semi);
disp(' ');
disp('Error Stats for \sigma in L^2(\Omega) and h^{1/2} * L^2(Skel):');
disp(' ');
kk_vec = (1:1:Num_Refine)';
h_vec = 0.5.^kk_vec;
Skel_L2_h_half = Error_Info.sig_Skel_L2 .* h_vec.^(1/2);
display_error_stats(Sim_Info,'sig, L^2(O)',Error_Info.sig_L2,'sig, ~L^2(Sk)',Skel_L2_h_half);
disp(' ');
% disp(' N_T (4^k) | EOC for u (H^1) | EOC for \sigma (L^2(Omega)) |');
% u_H1_EOC = -log2(Error_Info.u_H1_semi(2:end)./Error_Info.u_H1_semi(1:end-1));
% u_H2_EOC = -log2(Error_Info.u_H2_semi(2:end)./Error_Info.u_H2_semi(1:end-1));
% sig_EOC = -log2(Error_Info.sig_L2(2:end)./Error_Info.sig_L2(1:end-1));
% OUT_1 = [log2(Sim_Info.elems)/2, [0; u_H1_EOC], [0; sig_EOC]];
% OUT_1
disp('Error Stats for w in L^\infty(\Omega) and w in H^2(T_{h}):');
disp(' ');
display_error_stats(Sim_Info,'w, L^inf(O)',Error_Info.u_L_inf,'w, H^2(T_h)',Error_Info.u_H2_semi);
disp(' ');
disp('Error Stats for \sigma in L^2(\Gamma) and normal vector in L^2(\Gamma):');
disp(' ');
display_error_stats(Sim_Info,'sig, L^2(G)',Error_Info.sig_Gamma_L2,'n, L^2(G)',Error_Info.normal_L2);
disp(' ');
% disp(' ');
% disp(' N_T (4^k) | EOC for \sigma (L^2(Gamma)) | EOC for h^{1/2} (n'' \sigma n) (L^2(Skel))');
% sig_nn_Gamma_EOC = -log2(Error_Info.sig_Gamma_L2(2:end)./Error_Info.sig_Gamma_L2(1:end-1));
% sig_nn_Skel_EOC = -log2(Error_Info.sig_Skel_L2(2:end)./Error_Info.sig_Skel_L2(1:end-1));
% OUT_2 = [log2(Sim_Info.elems)/2, [0; sig_nn_Gamma_EOC], [0; (sig_nn_Skel_EOC + 0.5)]];
% OUT_2
% disp(' ');
% disp(' N_T (4^k) | EOC for normal (L^2(Gamma)) | EOC for u (H^2_h) ');
% normal_Gamma_EOC = -log2(Error_Info.normal_L2(2:end)./Error_Info.normal_L2(1:end-1));
% OUT_3 = [log2(Sim_Info.elems)/2, [0; normal_Gamma_EOC], [0; u_H2_EOC]];
% OUT_3
disp('Error Stats for the point displacement error at the center:');
disp(' ');
displace_err = u_origin - exact_u_func(0,0);
display_displacement_stats(Sim_Info,u_origin,displace_err);
disp(' ');
% evaluate given smooth function
%W_X = W_Space.Get_DoF_Coord(Mesh,G_Space,Geo_Points);
BB = Mesh.Bounding_Box();
BB(1) = BB(1) - 0.1;
BB(2) = BB(2) + 0.1;
BB(3) = BB(3) - 0.1;
BB(4) = BB(4) + 0.1;
BB = BB(1:4);
QT = mexQuadtree(W_X(:,1:2),BB);
[Mesh_to_W_X, Dist] = QT.kNN_Search(Mesh.Points(:,1:2),1);
P1_u = u_soln(Mesh_to_W_X,1);
%[Center_W_X_ind, Dist] = QT.kNN_Search([0 0],1);
%Dist
delete(QT);
P1_u_error = P1_u - I_u_exact(Mesh_to_W_X,1);
disp('Displacement L^\infty error:');
Error_Info.u_L_inf(end)
%max(abs(u_soln - I_u_exact))
figure;
trisurf(Mesh.ConnectivityList,Mesh.Points(:,1),Mesh.Points(:,2),P1_u_error);
shading interp;
% AX = Mesh.Bounding_Box;
% view(2);
% axis(AX);
% axis equal;
% axis(AX);
title('Numerical Solution (displacement error)');
xlabel('X');
ylabel('Y');
colorbar;
% compute t, n
W_X_MAG = sqrt(sum(W_X.^2,2)) + 1e-15;
W_X_normal = W_X;
W_X_normal(:,1) = W_X(:,1) ./ W_X_MAG;
W_X_normal(:,2) = W_X(:,2) ./ W_X_MAG;
W_X_tangent = [-W_X_normal(:,2), W_X_normal(:,1)];
sig_error_nn = sig_error_W_X(:,1) .* W_X_normal(:,1) .* W_X_normal(:,1)...
+ sig_error_W_X(:,2) .* W_X_normal(:,1) .* W_X_normal(:,2)...
+ sig_error_W_X(:,3) .* W_X_normal(:,2) .* W_X_normal(:,1)...
+ sig_error_W_X(:,4) .* W_X_normal(:,2) .* W_X_normal(:,2);
%
sig_error_nt = sig_error_W_X(:,1) .* W_X_normal(:,1) .* W_X_tangent(:,1)...
+ sig_error_W_X(:,2) .* W_X_normal(:,1) .* W_X_tangent(:,2)...
+ sig_error_W_X(:,3) .* W_X_normal(:,2) .* W_X_tangent(:,1)...
+ sig_error_W_X(:,4) .* W_X_normal(:,2) .* W_X_tangent(:,2);
%
sig_error_tt = sig_error_W_X(:,1) .* W_X_tangent(:,1) .* W_X_tangent(:,1)...
+ sig_error_W_X(:,2) .* W_X_tangent(:,1) .* W_X_tangent(:,2)...
+ sig_error_W_X(:,3) .* W_X_tangent(:,2) .* W_X_tangent(:,1)...
+ sig_error_W_X(:,4) .* W_X_tangent(:,2) .* W_X_tangent(:,2);
%
sig_error_ortho = [sig_error_nn, sig_error_nt, sig_error_nt, sig_error_tt];
sig_error_Mask = W_X_MAG > (1 + 4e-2);
sig_error_ortho(sig_error_Mask,:) = 0;
% disp('Max sig_error_W_X:');
% max(abs(sig_error_W_X(:)))
%
% T1 = abs(sig_error_W_X(:));
% T1 = sort(T1);
% T1(1:10,1)
%
% T1(end-10:end,1)
%
% max(abs(sig_error_ortho(:)))
figure;
for kk = 1:4
subplot(2,2,kk);
%trisurf(Mesh.ConnectivityList,Mesh.Points(:,1),Mesh.Points(:,2),sig_soln_W_X(Mesh_to_W_X,kk));
%trisurf(Mesh.ConnectivityList,Mesh.Points(:,1),Mesh.Points(:,2),sig_error_W_X(Mesh_to_W_X,kk));
trisurf(Mesh.ConnectivityList,Mesh.Points(:,1),Mesh.Points(:,2),sig_error_ortho(Mesh_to_W_X,kk));
%plot3(W_X(:,1),W_X(:,2),sig_error_W_X,'k.','MarkerSize',4);
shading interp;
AX = Mesh.Bounding_Box;
% view(2);
% axis(AX);
% axis equal;
% axis(AX);
%index_str = {'11', '12', '21', '22'};
index_str = {'nn', 'nt', 'tn', 'tt'};
title(['Numerical Solution (\sigma_{', index_str{kk}, '} error)']);
xlabel('X');
ylabel('Y');
colorbar;
end
figure;
trisurf(Mesh.ConnectivityList,Mesh.Points(:,1),Mesh.Points(:,2),P1_u);
shading interp;
%trimesh(Mesh.ConnectivityList,Mesh.Points(:,1),Mesh.Points(:,2));
% hold on;
% % W_DoFs_Gamma = W_Space.Get_DoFs_On_Subdomain(Mesh,'Gamma');
% % W_X_Gamma = W_X(W_DoFs_Gamma,:);
% % plot(W_X_Gamma(:,1),W_X_Gamma(:,2),'md');
% V_DoFs_Gamma = V_Space.Get_Fixed_DoFs(Mesh);
% V_X = V_Space.Get_DoF_Coord(Mesh,G_Space,Geo_Points);
% V_X_Gamma = V_X(V_DoFs_Gamma,:);
% disp('Number of V-DoFs on boundary:');
% length(V_DoFs_Gamma)
% disp('Error Check: number of edges in boundary:');
% GM = Mesh.Get_Global_Subdomain('Gamma');
% size(GM,1)
% plot(V_X_Gamma(:,1),V_X_Gamma(:,2),'md');
% hold off;
AX = Mesh.Bounding_Box;
AX = AX(1:4);
view(2);
axis(AX);
axis equal;
axis(AX);
title('Numerical Solution (displacement)');
xlabel('X');
ylabel('Y');
colorbar;
% plot the error decay
FH_error = figure('Renderer','painters','PaperPositionMode','auto','Color','w');
Order_1_Line = 10.0 * 2.^(-Refine_Vec);
Order_2_Line = 15.0 * 4.^(-Refine_Vec);
Order_3_Line = 15.0 * 8.^(-Refine_Vec);
Order_4_Line = 15.0 * 16.^(-Refine_Vec);
semilogy(Refine_Vec,Error_Info.u_H1_semi,'k-*',...
Refine_Vec,Error_Info.sig_L2,'m-*',...
Refine_Vec,Order_1_Line,'r-d',...
Refine_Vec,Order_2_Line,'b-d',...
Refine_Vec,Order_3_Line,'g-d',...
Refine_Vec,Order_4_Line,'y-d');
xlabel('Refinement Level');
ylabel('Error');
title('Convergence Rate of Numerical Solution');
%axis([Refine_Vec(1) Refine_Vec(end) 1e-3 1e2]);
legend({'$\| u_h - u \|_{H^1(\Omega)}$','$\| \sigma_h - \sigma \|_{L^2(\Omega)}$',...
'$O(h)$ line','$O(h^2)$ line','$O(h^3)$ line','$O(h^4)$ line'},...
'Interpreter','latex','FontSize',12,'Location','best');
grid;
% u_origin
%
% Error_Info.u_H1_semi
% Error_Info.u_H2_semi
% Error_Info.sig_L2
% Error_Info.sig_Gamma_L2
Mesh
diary off;
% % save mesh
% Vtx = Geo_Points;
% Tri = double(G_Space.DoFmap);
%
% % Vtx = Mesh.Points;
% % Tri = Mesh.ConnectivityList;
%
% MT = MeshTriangle(Tri,Vtx,'Test');
% figure;
% MT.Plot;
%
% xmlmesh(Vtx,Tri,'xmlmesh_disk_2D.xml');
asfdasf
RefErrorDataFileName = fullfile(Main_Dir,'FEL_Execute_Bending_Plate_2D_REF_Data.mat');
% save(RefErrorDataFileName,'L2_Error_Vec','Small_Matrix_Error_Vec');
REF_DATA = load(RefErrorDataFileName);
% simple regression check
ERR_CHK1 = max(abs(REF_DATA.L2_Error_Vec - Error_Info.u_H1_semi));
ERR_CHK2 = max(abs(REF_DATA.Small_Matrix_Error_Vec - Small_Matrix_Error_Vec));
ERR_CHK = max(ERR_CHK1,ERR_CHK2);
% different computers should compute the same errors (up to round-off!)
status = 0; % init
if (ERR_CHK > 1e-10)
disp('HHJk on a curved disk in 2-D: convergence error failed!');
ERR_CHK
status = 1;
end
end
function [G_Space, Geo_Points, Geo_Points_hat, V_Space, W_Space, SkDG_Space, OmegaDG_Space] =...
create_FE_spaces(Main_Dir,Mesh,deg_geo,deg_k,Mesh_type,BC_type,PD,MM)
%
% create GeoElementSpace
Pk_Omega = eval(['lagrange_deg', num2str(deg_geo), '_dim2();']);
G_Space_RefElem = ReferenceFiniteElement(Pk_Omega);
G_Space = GeoElementSpace('G_h',G_Space_RefElem,Mesh);
if (deg_geo==1)
G_DoFmap = uint32(Mesh.ConnectivityList);
else
G_DoFmap = UNIT_TEST_mex_Bending_Plate_2D_G_Space_DoF_Allocator(uint32(Mesh.ConnectivityList));
end
G_Space = G_Space.Set_DoFmap(Mesh,uint32(G_DoFmap));
G_Space = G_Space.Set_mex_Dir(Main_Dir,'UNIT_TEST_mex_Interp_G_Space_Bending_Plate_2D');
% BEGIN: define the higher order domain
Geo_Points_hat = G_Space.Get_Mapping_For_Piecewise_Linear_Mesh(Mesh);
% initially starts as a piecewise deg k polynomial (Pk function) interpolating a
% piecewise linear (P1) function (representing the initial mesh)
Geo_Points = Geo_Points_hat;
if or(strcmp(Mesh_type,'refined_disk'),strcmp(Mesh_type,'disk_n_gon'))
if (deg_geo > 1)
SI = Mesh.Get_Subdomain_Index('Gamma');
Bdy_Tri_Data = double(Mesh.Subdomain(SI).Data);
% Bdy_Tri_Data
% figure;
% Mesh.Plot_Subdomain('Gamma');
Geo_Points = Higher_Order_Elem(G_Space,Geo_Points_hat(:,1:2),Bdy_Tri_Data(:,1),Bdy_Tri_Data(:,2));
%Geo_Points = [Geo_Points, 0*Geo_Points(:,1)];
end
elseif strcmp(Mesh_type,'circle_alt')
if (deg_geo > 1)
SI = Mesh.Get_Subdomain_Index('Gamma');
Bdy_Tri_Data = double(Mesh.Subdomain(SI).Data);
% this comes out sorted!
% need to correlate
[LIA, LOCB] = ismember(MM.BdyTRI_Ind,Bdy_Tri_Data(:,1));
Bdy_Tri_Data_Alt = Bdy_Tri_Data(LOCB,:);
% Bdy_Tri_Data_Alt(:,2)
% Mesh.ConnectivityList(Bdy_Tri_Data_Alt(:,1),:)
% MM.BdyEDGE
Geo_Points = Get_Curved_Element_Mapping(G_Space,Geo_Points_hat(:,1:2),MM,Bdy_Tri_Data_Alt(:,1),Bdy_Tri_Data_Alt(:,2));
%Geo_Points = [Geo_Points, 0*Geo_Points(:,1)];
end
elseif strcmp(Mesh_type,'refined_disk_alt')
% here we take a special square mesh, and deform all elements
% find four separate groups of vertices
ANG = atan2(Geo_Points_hat(:,2),Geo_Points_hat(:,1));
Right_SEC = (ANG <= 45 * (pi/180)) & (ANG >= -45 * (pi/180));
Top_SEC = (ANG < 135 * (pi/180)) & (ANG > 45 * (pi/180));
Bot_SEC = (ANG > -135 * (pi/180)) & (ANG < -45 * (pi/180));
Left_SEC = ~(Right_SEC | Top_SEC | Bot_SEC);
% get other masks
Pos_x = Geo_Points_hat(:,1) >= 0;
Neg_x = ~Pos_x;
Pos_y = Geo_Points_hat(:,2) >= 0;
Neg_y = ~Pos_y;
% define disk function
f_disk = @(s) sqrt(1 - s.^2);
Geo_Points = Geo_Points_hat; % init
% map the right
displace_pos = @(x,y) ( (f_disk(y) - x) ./ (1e-15 + (1/sqrt(2)) - y) ) .* (x - y) + x;
displace_neg = @(x,y) ( (f_disk(y) - x) ./ (1e-15 + (1/sqrt(2)) + y) ) .* (x + y) + x;
Rt_Pos_y = Pos_y & Right_SEC;
Rt_Neg_y = Neg_y & Right_SEC;
Geo_Points(Rt_Pos_y,:) = [displace_pos(Geo_Points_hat(Rt_Pos_y,1),Geo_Points_hat(Rt_Pos_y,2)),...
Geo_Points_hat(Rt_Pos_y,2)];
%
Geo_Points(Rt_Neg_y,:) = [displace_neg(Geo_Points_hat(Rt_Neg_y,1),Geo_Points_hat(Rt_Neg_y,2)),...
Geo_Points_hat(Rt_Neg_y,2)];
%
% map the left
displace_pos = @(x,y) ( (-f_disk(y) - x) ./ (-1e-15 + (-1/sqrt(2)) + y) ) .* (x + y) + x;
displace_neg = @(x,y) ( (-f_disk(y) - x) ./ (-1e-15 + (-1/sqrt(2)) - y) ) .* (x - y) + x;
Lt_Pos_y = Pos_y & Left_SEC;
Lt_Neg_y = Neg_y & Left_SEC;
Geo_Points(Lt_Pos_y,:) = [displace_pos(Geo_Points_hat(Lt_Pos_y,1),Geo_Points_hat(Lt_Pos_y,2)),...
Geo_Points_hat(Lt_Pos_y,2)];
%
Geo_Points(Lt_Neg_y,:) = [displace_neg(Geo_Points_hat(Lt_Neg_y,1),Geo_Points_hat(Lt_Neg_y,2)),...
Geo_Points_hat(Lt_Neg_y,2)];
%
% map the top
displace_pos = @(x,y) ( (f_disk(x) - y) ./ (1e-15 + (1/sqrt(2)) - x) ) .* (y - x) + y;
displace_neg = @(x,y) ( (f_disk(x) - y) ./ (1e-15 + (1/sqrt(2)) + x) ) .* (y + x) + y;
Top_Pos_x = Pos_x & Top_SEC;
Top_Neg_x = Neg_x & Top_SEC;
Geo_Points(Top_Pos_x,:) = [Geo_Points_hat(Top_Pos_x,1),...
displace_pos(Geo_Points_hat(Top_Pos_x,1),Geo_Points_hat(Top_Pos_x,2))];
%
Geo_Points(Top_Neg_x,:) = [Geo_Points_hat(Top_Neg_x,1),...
displace_neg(Geo_Points_hat(Top_Neg_x,1),Geo_Points_hat(Top_Neg_x,2))];
%
% map the bottom
displace_pos = @(x,y) ( (-f_disk(x) - y) ./ (-1e-15 + (-1/sqrt(2)) + x) ) .* (y + x) + y;
displace_neg = @(x,y) ( (-f_disk(x) - y) ./ (-1e-15 + (-1/sqrt(2)) - x) ) .* (y - x) + y;
Bot_Pos_x = Pos_x & Bot_SEC;
Bot_Neg_x = Neg_x & Bot_SEC;
Geo_Points(Bot_Pos_x,:) = [Geo_Points_hat(Bot_Pos_x,1),...
displace_pos(Geo_Points_hat(Bot_Pos_x,1),Geo_Points_hat(Bot_Pos_x,2))];
%
Geo_Points(Bot_Neg_x,:) = [Geo_Points_hat(Bot_Neg_x,1),...
displace_neg(Geo_Points_hat(Bot_Neg_x,1),Geo_Points_hat(Bot_Neg_x,2))];
%
else
disp('WARNING! Assuming mesh is a square...');
disp('No need to have a fancy mapping!');
end
% END: define the higher order domain
% % plot the higher order domain
% figure;
% Temp_Pts = Mesh.Points;
% qm = trimesh(Mesh.ConnectivityList,Temp_Pts(:,1),Temp_Pts(:,2),0*Temp_Pts(:,2));
% set(qm,'EdgeColor','k');
% hold on;
% plot(Geo_Points_hat(:,1),Geo_Points_hat(:,2),'gs');
% plot(Geo_Points(:,1),Geo_Points(:,2),'k*');
% % quiver(vx(1).dof(:,1),vx(1).dof(:,2),Tri_to_Gamma_vn(:,1),Tri_to_Gamma_vn(:,2),'color','r');
% % quiver(vx(2).dof(:,1),vx(2).dof(:,2),Tri_to_Gamma_vn(:,1),Tri_to_Gamma_vn(:,2),'color','b');
%
% % Vec_Internal = Geo_Points(Internal_DoF,:) - Geo_Points_hat(Internal_DoF,:);
% % VEC_INT = Normalize_Vector_Field(Vec_Internal);
% % quiver(Geo_Points_hat(Internal_DoF,1),Geo_Points_hat(Internal_DoF,2),VEC_INT(:,1),VEC_INT(:,2),'color','m');
% % plot(Geo_Points_hat(Internal_DoF,1),Geo_Points_hat(Internal_DoF,2),'pc');
%
% PD.Plot_Boundary(10000);
% % %cylinder(1,10000);
%
% % plot(Geo_Points_hat(Tri_to_Gamma_DoF(:,2),1),Geo_Points_hat(Tri_to_Gamma_DoF(:,2),2),'rd');
% % plot(Geo_Points_hat(Tri_to_Gamma_DoF(:,3),1),Geo_Points_hat(Tri_to_Gamma_DoF(:,3),2),'bp');
% % plot(Geo_Points_hat(DoFs_on_Gamma_Edge,1),Geo_Points_hat(DoFs_on_Gamma_Edge,2),'mp');
% % plot(new_dof_ave(:,1),new_dof_ave(:,2),'rd');
% % plot(old_dof_ave(:,1),old_dof_ave(:,2),'mp');
% hold off;
% view(2);
% axis equal;
% % plot skeleton
% figure;
% subplot(1,2,1);
% SK_plus = Mesh.Output_Subdomain_Mesh('Skeleton_Plus');
% SK_plus.Plot;
% subplot(1,2,2);
% SK_minus = Mesh.Output_Subdomain_Mesh('Skeleton_Minus');
% SK_minus.Plot;
clear DoFs_on_Gamma GP_Gamma GP_Dist;
% define FE spaces
P_k_plus_1 = eval(['lagrange_deg', num2str(deg_k+1), '_dim2();']);
P_k_plus_1_RefElem = ReferenceFiniteElement(P_k_plus_1);
W_Space = FiniteElementSpace('W_h', P_k_plus_1_RefElem, Mesh, 'Omega');
W_DoFmap = UNIT_TEST_mex_Bending_Plate_2D_W_Space_DoF_Allocator(uint32(Mesh.ConnectivityList));
W_Space = W_Space.Set_DoFmap(Mesh,uint32(W_DoFmap));
if or(strcmpi('clamped',BC_type),strcmpi('simply_supported',BC_type))
% set fixed DoFs
W_Space = W_Space.Append_Fixed_Subdomain(Mesh,'Gamma');
else
% don't impose anything!
end
HHJ_k = eval(['hellan_herrmann_johnson_deg', num2str(deg_k), '_dim2();']);
HHJ_RefElem = ReferenceFiniteElement(HHJ_k);
V_Space = FiniteElementSpace('V_h', HHJ_RefElem, Mesh, 'Omega');
V_DoFmap = UNIT_TEST_mex_Bending_Plate_2D_V_Space_DoF_Allocator(uint32(Mesh.ConnectivityList));
V_Space = V_Space.Set_DoFmap(Mesh,uint32(V_DoFmap));
if or(strcmpi('free',BC_type),strcmpi('simply_supported',BC_type))
% set fixed DoFs
V_Space = V_Space.Append_Fixed_Subdomain(Mesh,'Gamma');
else
% don't impose anything!
end
% define DG spaces
P_k_DG = eval(['lagrange_deg', num2str(deg_k), '_dim1(''DG'');']);
P_k_DG_RefElem = ReferenceFiniteElement(P_k_DG);
SkDG_Space = FiniteElementSpace('SkDG', P_k_DG_RefElem, Mesh, 'Skeleton_Plus');
SkEdges = Mesh.Get_Global_Subdomain('Skeleton_Plus');
Num_Edges = size(SkEdges,1);
Num_Edge_DoF = deg_k + 1;
Dmap_transpose = zeros(Num_Edges,Num_Edge_DoF)';
DoF_Indices = (1:1:(Num_Edges*Num_Edge_DoF))';
Dmap_transpose(:) = DoF_Indices;
SkDG_DoFmap = Dmap_transpose';
SkDG_Space = SkDG_Space.Set_DoFmap(Mesh,uint32(SkDG_DoFmap));
if or(strcmpi('free',BC_type),strcmpi('simply_supported',BC_type))
% set fixed DoFs
SkDG_Space = SkDG_Space.Append_Fixed_Subdomain(Mesh,'Gamma');
else
% don't impose anything!
end
if (deg_k > 0)
P_k_minus_1_DG = eval(['lagrange_deg', num2str(deg_k-1), '_dim2(''DG'');']);
P_k_minus_1_DG_RefElem = ReferenceFiniteElement(P_k_minus_1_DG);
OmegaDG_Space = FiniteElementSpace('OmegaDG', P_k_minus_1_DG_RefElem, Mesh, 'Omega');
Num_Tri = Mesh.Num_Cell();
Num_Tri_DoF = round((1/2) * deg_k * (deg_k + 1));
Dmap_transpose = zeros(Num_Tri,Num_Tri_DoF)';
DoF_Indices = (1:1:(Num_Tri*Num_Tri_DoF))';
Dmap_transpose(:) = DoF_Indices;
OmegaDG_DoFmap = Dmap_transpose';
OmegaDG_Space = OmegaDG_Space.Set_DoFmap(Mesh,uint32(OmegaDG_DoFmap));
else
OmegaDG_Space = [];
end
end
function status = display_displacement_stats(SI,displace,err_vec)
EOC = -log2( abs(err_vec(2:end)) ./ abs(err_vec(1:end-1)) );
EOC = [0; EOC];
NR = length(displace);
STR_sides = num2str(SI.sides);
STR_elems = num2str(SI.elems);
STR_dofs = num2str(SI.dofs);
STR_displ = num2str(displace,'%1.7G');
STR_err = num2str(err_vec,'%1.7G');
STR_rel_err = num2str(err_vec ./ displace,'%1.7G');
STR_EOC = num2str(EOC,'%1.7G');
disp([blanks(size(STR_sides,2)-3), 'sides', ' |', blanks(size(STR_elems,2)-4), 'elems', ' |',...
blanks(size(STR_dofs,2)-3), 'DoFs', ' |', blanks(size(STR_displ,2)-7), 'displace', ' |',...
blanks(size(STR_err,2)-4), 'error', ' |', blanks(size(STR_rel_err,2)-9), 'rel. error', ' |',...
blanks(size(STR_EOC,2)-5), 'EOC']);
disp([repmat(' ',NR,1), ...
STR_sides, repmat(' | ',NR,1), ...
STR_elems, repmat(' | ',NR,1), ...
STR_dofs, repmat(' | ',NR,1), ...
STR_displ, repmat(' | ',NR,1), ...
STR_err, repmat(' | ',NR,1), ...
STR_rel_err, repmat(' | ',NR,1), ...
STR_EOC ])
%
status = 0;
end
function status = display_error_stats(SI,name_err_1,err_1,name_err_2,err_2)
EOC_1 = -log2( abs(err_1(2:end)) ./ abs(err_1(1:end-1)) );
EOC_1 = [0; EOC_1];
EOC_2 = -log2( abs(err_2(2:end)) ./ abs(err_2(1:end-1)) );
EOC_2 = [0; EOC_2];
NR = length(err_1);
STR_sides = num2str(SI.sides);
STR_elems = num2str(SI.elems);
STR_dofs = num2str(SI.dofs);
STR_err_1 = num2str(err_1,'%1.10G');
STR_err_2 = num2str(err_2,'%1.10G');
STR_EOC_1 = num2str(EOC_1,'%1.10G');
STR_EOC_2 = num2str(EOC_2,'%1.10G');
disp([blanks(size(STR_sides,2)-3), 'sides', ' |', blanks(size(STR_elems,2)-4), 'elems', ' |',...
blanks(size(STR_dofs,2)-3), 'DoFs', ' |',...
blanks(size(STR_err_1,2)-length(name_err_1)+1), name_err_1, ' |', blanks(size(STR_EOC_1,2)-2), 'EOC', ' |', ...
blanks(size(STR_err_2,2)-length(name_err_2)+1), name_err_2, ' |', blanks(size(STR_EOC_2,2)-2), 'EOC']);
disp([repmat(' ',NR,1), ...
STR_sides, repmat(' | ',NR,1), ...
STR_elems, repmat(' | ',NR,1), ...
STR_dofs, repmat(' | ',NR,1), ...
STR_err_1, repmat(' | ',NR,1), ...
STR_EOC_1, repmat(' | ',NR,1), ...
STR_err_2, repmat(' | ',NR,1), ...
STR_EOC_2 ])
%
status = 0;
end
|
github
|
eardi/sm-fpca-master
|
DiffGeo_HHJk_Surface.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Unit_Test/Mixed_HHJ/HHJk_Surface/DiffGeo_HHJk_Surface.m
| 3,852 |
utf_8
|
2329d8c3b439918d7a4972f03e34f5f4
|
function [soln_func, soln_surf_grad_func, soln_surf_hess, f_func, normal_vec_func] = DiffGeo_HHJk_Surface(surf_func,soln_tilde,vars)
%DiffGeo_HHJk_Surface
% Copyright (c) 03-30-2018, Shawn W. Walker
% note: surf_func is a height function
u = vars(1);
v = vars(2);
soln_func = matlabFunction(soln_tilde);
soln_func
% define surface parameterization
Xmap = [u;v;surf_func(u,v)];
% compute metric
Xmap_du = diff(Xmap,u,1);
Xmap_dv = diff(Xmap,v,1);
J = [Xmap_du, Xmap_dv];
g = transpose(J) * J;
% compute the inverse metric
g_inv = inv(g);
%det_g = det(g);
% g
% g_inv
% det_g
% get grad(u), hess(u)
[soln_surf_grad, soln_surf_hess] = get_surf_grad_surf_hess(u,v,soln_tilde,J,g,g_inv);
soln_surf_grad_func = matlabFunction(soln_surf_grad);
%soln_surf_grad_func
% soln_surf_hess_func = matlabFunction(soln_surf_hess(:)');
% soln_surf_hess_func
soln_surf_hess
% get Laplace-Beltrami
soln_surf_lap = trace(soln_surf_hess);
soln_surf_lap = simplify(soln_surf_lap);
% get grad(\Delta u), hess(\Delta u)
[~, SL_hess] = get_surf_grad_surf_hess(u,v,soln_surf_lap,J,g,g_inv);
soln_surf_biharmonic = trace(SL_hess);
symbolic_f = simplify(soln_surf_biharmonic);
%symbolic_f
% RHS f term
f_func = matlabFunction(symbolic_f);
f_func
% compute the normal vector
NV_temp = cross(Xmap_du,Xmap_dv);
NV_temp_norm = sqrt(transpose(NV_temp) * NV_temp);
Normal_Vector = NV_temp / NV_temp_norm;
normal_vec_func = matlabFunction(Normal_Vector);
%normal_vec_func
end
function [surf_grad, surf_hess] = get_surf_grad_surf_hess(u,v,func,J,g,g_inv)
% % compute derivatives of soln (in reference domain)
% func_du = diff(func,u,1);
% func_dv = diff(func,v,1);
%
% % compute the surface gradient of the solution (in reference coordinates)
% surf_grad = ([func_du, func_dv] * g_inv * transpose(J))';
% surf_grad = simplify(surf_grad);
surf_grad = get_surf_grad_only(u,v,func,J,g_inv);
% compute the COVARIANT surface hessian!
% compute derivatives of soln (in reference domain)
func_grad = [diff(func,u,1); diff(func,v,1)];
% compute hessian of soln (in reference domain)
func_hess = [diff(func,u,u), diff(func,u,v);
diff(func,v,u), diff(func,v,v)];
%
% differentiate metric
grad_metric(2).mat = [];
grad_metric(1).mat = simplify(diff(g,u));
grad_metric(2).mat = simplify(diff(g,v));
% compute the Christoffel symbols (2nd kind)
Gamma(2).ij = sym(zeros(2,2));
for kk=1:2
for ii=1:2
for jj=1:2
TEMP = sym(0);
for ll=1:2
TEMP = TEMP + g_inv(kk,ll) * ( grad_metric(ii).mat(ll,jj) + grad_metric(jj).mat(ii,ll) - grad_metric(ll).mat(ii,jj) );
end
Gamma(kk).ij(ii,jj) = (1/2) * simplify(TEMP);
end
end
end
% compute "local" term
local_hess = func_hess - ( func_grad(1) * Gamma(1).ij + func_grad(2) * Gamma(2).ij );
local_hess = simplify(local_hess);
% map to surface
J_g_inv_MAT = J * g_inv;
surf_hess = J_g_inv_MAT * local_hess * (transpose(J_g_inv_MAT));
% % compute derivatives in reference domain
% surf_grad_du = diff(surf_grad,u,1);
% surf_grad_dv = diff(surf_grad,v,1);
%
% % compute the surface gradient of the solution (in reference coordinates)
% surf_hess_row(3).vec = [];
% for ii = 1:3
% surf_hess_row(ii).vec = [surf_grad_du(ii), surf_grad_dv(ii)] * g_inv * transpose(J);
% end
% surf_hess = [surf_hess_row(1).vec;
% surf_hess_row(2).vec;
% surf_hess_row(3).vec];
% %
% surf_hess = simplify(surf_hess);
end
function surf_grad = get_surf_grad_only(u,v,func,J,g_inv)
% compute derivatives of soln (in reference domain)
func_du = diff(func,u,1);
func_dv = diff(func,v,1);
% compute the surface gradient of the solution (in reference coordinates)
surf_grad = ([func_du, func_dv] * g_inv * transpose(J))';
surf_grad = simplify(surf_grad);
end
|
github
|
eardi/sm-fpca-master
|
Output_CPP_Eval_Extension.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Transformer/@Hdivdiv_Trans/Output_CPP_Eval_Extension.m
| 1,276 |
utf_8
|
3ce6eb129636b9092f7c76021a3c008f
|
function CPP_Eval = Output_CPP_Eval_Extension(obj,FIELD_str,Components)
%Output_CPP_Eval_Extension
%
% This outputs a string representing the C++ evaluation code for the given
% variable name.
%
% Components = [basis_comp_1, basis_comp_2, comp_1, comp_2, etc...]
% Copyright (c) 03-22-2018, Shawn W. Walker
% peel off the basis component
Basis_Comp = Components(1:2);
Components = Components(3:end);
% if strcmp(FIELD_str,'Orientation')
% error('you don''t need this!');
if strcmp(FIELD_str,'Val')
Basis_Comp_C_index_STR = Get_Index_String(Basis_Comp);
CPP_Eval = ['.m', Basis_Comp_C_index_STR];
% elseif strcmp(FIELD_str,'Div')
% CPP_Eval = ['.a', ''];
% elseif strcmp(FIELD_str,'Grad')
% Grad_Comp_C_index_STR = Get_Index_String(Components(1));
% CPP_Eval = ['.v', Grad_Comp_C_index_STR];
% elseif strcmp(FIELD_str,'Hess')
% Comp_1_C_index_STR = Get_Index_String(Components(1));
% Comp_2_C_index_STR = Get_Index_String(Components(2));
% CPP_Eval = ['.m', Comp_1_C_index_STR, Comp_2_C_index_STR];
else
error('Not valid!');
end
end
function INDEX_str = Get_Index_String(Index)
% use C-style indexing
INDEX_str = ['[', num2str(Index(1) - 1), ']', '[', num2str(Index(2) - 1), ']'];
end
|
github
|
eardi/sm-fpca-master
|
Output_CPP_Eval_Extension.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Transformer/@Hcurl_Trans/Output_CPP_Eval_Extension.m
| 1,722 |
utf_8
|
f271a34bc251f262655357e05cdafcfa
|
function CPP_Eval = Output_CPP_Eval_Extension(obj,FIELD_str,Components)
%Output_CPP_Eval_Extension
%
% This outputs a string representing the C++ evaluation code for the given
% variable name.
%
% Components = [basis_comp_1, basis_comp_2, comp_1, comp_2, etc...]
% Copyright (c) 10-17-2016, Shawn W. Walker
% peel off the basis component
Basis_Comp = Components(1:2);
Components = Components(3:end);
if strcmp(FIELD_str,'Orientation')
error('you don''t need this!');
elseif strcmp(FIELD_str,'Val')
Vec_Comp_C_index_STR = Get_Index_String(Basis_Comp(1));
CPP_Eval = ['.v', Vec_Comp_C_index_STR];
elseif strcmp(FIELD_str,'Curl')
TD = obj.GeoMap.TopDim;
GD = obj.GeoMap.GeoDim;
if (TD==2)
if (GD==2)
% curl is a scalar
CPP_Eval = ['.a', ''];
elseif (GD==3)
error('Not implemented!');
else
error('Invalid!');
end
elseif (TD==3)
% curl is a vector
Vec_Comp_C_index_STR = Get_Index_String(Basis_Comp(1));
CPP_Eval = ['.v', Vec_Comp_C_index_STR];
else
error('Not implemented or invalid!');
end
% elseif strcmp(FIELD_str,'Grad')
% Grad_Comp_C_index_STR = Get_Index_String(Components(1));
% CPP_Eval = ['.v', Grad_Comp_C_index_STR];
% elseif strcmp(FIELD_str,'Hess')
% Comp_1_C_index_STR = Get_Index_String(Components(1));
% Comp_2_C_index_STR = Get_Index_String(Components(2));
% CPP_Eval = ['.m', Comp_1_C_index_STR, Comp_2_C_index_STR];
else
error('Not valid!');
end
end
function INDEX_str = Get_Index_String(Index)
% use C-style indexing
INDEX_str = ['[', num2str(Index - 1), ']'];
end
|
github
|
eardi/sm-fpca-master
|
Premap_Basis_in_2D.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Transformer/@Hcurl_Trans/private/Premap_Basis_in_2D.m
| 1,746 |
utf_8
|
e5cb527d427b07a5ad76004b9f45763c
|
function Sign_Change = Premap_Basis_in_2D(Mesh_Orient,All_Edge_DoFs,Num_Basis)
%Premap_Basis_in_2D
%
% This is used by the H(curl) elements for pre-mapping basis functions to
% adjust for different edge orientations.
%
% Sign_Change = Premap_Basis_in_2D(Mesh_Orient,All_Facet_DoFs,Num_Basis);
%
% Mesh_Orient: NxE vector indicating actual orientation of mesh elements
% (N is the number of elements; E is the number of element
% edges.)
% Example: [+1, -1, +1; ...] (E = 3)
% Elem #1: edge 1 and edge 3 are positively oriented;
% edge 2 is negative, etc...
% All_Edge_DoFs: cell array of sets of DoFs attached to all edges.
% Num_Basis: number of basis functions in the element.
%
% Sign_Change: NxB matrix, where B = number of basis functions:
% +1 = no sign change.
% -1 = flip sign of corresponding basis function.
% Rows correspond to rows of "Mesh_Orient".
% Copyright (c) 10-18-2016, Shawn W. Walker
Num_Elem = size(Mesh_Orient,1);
Num_Edges = size(Mesh_Orient,2);
Sign_Change = ones(Num_Elem,Num_Basis); % init
% loop through the local edges of the mesh elements
for ei = 1:Num_Edges
Edge_Sign = Mesh_Orient(:,ei);
Neg_Mask = (Edge_Sign==-1);
% gets DoF indices on the current edge
DoFs_On_Edge = get_dofs_on_edge(All_Edge_DoFs,ei);
% flip necessary signs
Sign_Change(Neg_Mask,DoFs_On_Edge) = -1;
end
end
function DoFs = get_dofs_on_edge(All_Edge_DoFs,Edge_Index)
DoFs = []; % init
for ci = 1:length(All_Edge_DoFs)
DoF_Set = All_Edge_DoFs{ci};
DI = DoF_Set(Edge_Index,:);
DoFs = [DoFs; DI(:)];
end
end
|
github
|
eardi/sm-fpca-master
|
test_H1_Trans.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Transformer/Unit_Test/test_H1_Trans.m
| 3,006 |
utf_8
|
c4952c0cdf9d5cc0c2354e4d677ed9cb
|
function status = test_H1_Trans()
%test_H1_Trans
%
% Test code for FELICITY class.
% Copyright (c) 05-19-2016, Shawn W. Walker
status = 0;
GM_test = Geometric_Trans('test',1,1,true);
FUNC1_test = H1_Trans('test',GM_test);
% make sure all the fields are there!
if (min(isfield(FUNC1_test.f,{'Val','Grad','d_ds','Hess','d2_ds2'}))==0)
status = 1;
end
% check all cases!
% (GeoDim,TopDim)
for gg=1:3
for tt=1:gg
if ~valid_f_struct(gg,tt,false)
status = 1;
end
if ~valid_f_struct(gg,tt,true)
status = 1;
end
end
end
%%%%%%%%%%%%%
if (status==0)
disp('Test passed!');
else
disp('Test failed!');
end
end
function TF = valid_f_struct(GeoDim,TopDim,LIN_MAP_TF)
TF = true; % init test result to passed
% define a map!
myMAP = Geometric_Trans('test',GeoDim,TopDim,LIN_MAP_TF);
myFUNC = H1_Trans('test',myMAP);
% ensure that the symbolic variables have the correct size!
if ~(min(abs(size(myFUNC.f.Val) - [1 1]))==0)
TF = false;
end
if ~(min(abs(size(myFUNC.f.Grad) - [1 GeoDim]))==0)
TF = false;
end
if ~isempty(myFUNC.f.d_ds)
if ~(min(abs(size(myFUNC.f.d_ds) - [1 1]))==0)
TF = false;
end
end
if ~(min(abs(size(myFUNC.f.Hess) - [GeoDim GeoDim]))==0)
TF = false;
end
if ~isempty(myFUNC.f.d2_ds2)
if ~(min(abs(size(myFUNC.f.d2_ds2) - [1 1]))==0)
TF = false;
end
end
% verify code generation!
Func_f( 1).Code = myFUNC.FUNC_Val_C_Code;
Func_f( 2).Code = myFUNC.FUNC_Val_special_C_Code;
Func_f( 3).Code = myFUNC.FUNC_d2_ds2_C_Code;
Func_f( 4).Code = myFUNC.FUNC_d_ds_C_Code;
Func_f( 5).Code = myFUNC.FUNC_Grad_C_Code;
Func_f( 6).Code = myFUNC.FUNC_Hess_C_Code;
Func_f( 7).Code = myFUNC.COEF_FUNC_Val_C_Code;
Func_f( 8).Code = myFUNC.COEF_FUNC_d2_ds2_C_Code;
Func_f( 9).Code = myFUNC.COEF_FUNC_d_ds_C_Code;
Func_f(10).Code = myFUNC.COEF_FUNC_Grad_C_Code;
Func_f(11).Code = myFUNC.COEF_FUNC_Hess_C_Code;
% load up reference data
if LIN_MAP_TF
LM_str = 'true';
else
LM_str = 'false';
end
DIR = fileparts(mfilename('fullpath'));
FN_str = ['Func_f_Codes_', num2str(GeoDim), num2str(TopDim), '_', LM_str, '.mat'];
FullFile_string = fullfile(DIR, FN_str);
RefData = load(FullFile_string,'Func_f');
%save(FullFile_string,'Func_f');
% check against reference data
for ind=1:length(Func_f(:))
STRUCTS_MATCH = isequal(RefData.Func_f(ind),Func_f(ind));
if ~STRUCTS_MATCH
TF = false; % test failed!
disp('RefData:');
LIN_MAP_TF
display_code_snippet(RefData.Func_f(ind).Code);
disp('Actual:');
LIN_MAP_TF
display_code_snippet(Func_f(ind).Code);
break;
end
end
end
function display_code_snippet(Code)
Code.Var_Name(1)
Code.Constant
for ii = 1:length(Code.Defn)
disp(Code.Defn(ii).line);
end
for ii = 1:length(Code.Eval_Snip)
disp(Code.Eval_Snip(ii).line);
end
end
|
github
|
eardi/sm-fpca-master
|
test_Geometric_Trans.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Transformer/Unit_Test/test_Geometric_Trans.m
| 7,370 |
utf_8
|
cbadddae9f798275055a84401ea17c40
|
function status = test_Geometric_Trans()
%test_Geometric_Trans
%
% Test code for FELICITY class.
% Copyright (c) 05-19-2016, Shawn W. Walker
status = 0;
MAP1_test = Geometric_Trans('test',3,3,true);
% make sure all the fields are there!
if (min(isfield(MAP1_test.PHI,{'Mesh_Size','Val','Grad','Metric','Det_Metric','Inv_Det_Metric','Inv_Metric',...
'Det_Jacobian','Det_Jacobian_with_quad_weight','Inv_Det_Jacobian','Inv_Grad',...
'Tangent_Vector','Normal_Vector','Tangent_Space_Projection',...
'Hess','Hess_Inv_Map','Grad_Metric','Grad_Inv_Metric',...
'Second_Fund_Form','Det_Second_Fund_Form','Inv_Det_Second_Fund_Form',...
'Total_Curvature_Vector','Total_Curvature','Gauss_Curvature','Shape_Operator'}))==0)
status = 1;
end
% check all cases!
% (GeoDim,TopDim)
for gg=1:3
for tt=1:gg
if ~valid_PHI_struct(gg,tt,false);
status = 1;
end
if ~valid_PHI_struct(gg,tt,true);
status = 1;
end
end
end
%%%%%%%%%%%%%
if (status==0)
disp('Test passed!');
else
disp('Test failed!');
end
end
function TF = valid_PHI_struct(GeoDim,TopDim,LIN_MAP_TF)
TF = true; % init test result to passed
% define a map!
myMAP = Geometric_Trans('test',GeoDim,TopDim,LIN_MAP_TF);
% ensure that the symbolic variables have the correct size!
if ~(min(abs(size(myMAP.PHI.Mesh_Size) - [1 1]))==0)
TF = false;
end
if ~(min(abs(size(myMAP.PHI.Val) - [GeoDim 1]))==0)
TF = false;
end
if ~(min(abs(size(myMAP.PHI.Grad) - [GeoDim TopDim]))==0)
TF = false;
end
if ~isempty(myMAP.PHI.Metric)
if ~(min(abs(size(myMAP.PHI.Metric) - [TopDim TopDim]))==0)
TF = false;
end
if ~(min(abs(size(myMAP.PHI.Det_Metric) - [1 1]))==0)
TF = false;
end
if ~(min(abs(size(myMAP.PHI.Inv_Det_Metric) - [1 1]))==0)
TF = false;
end
end
if ~isempty(myMAP.PHI.Inv_Metric)
if ~(min(abs(size(myMAP.PHI.Inv_Metric) - [TopDim TopDim]))==0)
TF = false;
end
end
if ~(min(abs(size(myMAP.PHI.Det_Jacobian) - [1 1]))==0)
TF = false;
end
if ~(min(abs(size(myMAP.PHI.Det_Jacobian_with_quad_weight) - [1 1]))==0)
TF = false;
end
if ~(min(abs(size(myMAP.PHI.Inv_Det_Jacobian) - [1 1]))==0)
TF = false;
end
if ~isempty(myMAP.PHI.Inv_Grad)
if ~(min(abs(size(myMAP.PHI.Inv_Grad) - [TopDim TopDim]))==0)
TF = false;
end
end
if ~isempty(myMAP.PHI.Tangent_Vector)
if ~(min(abs(size(myMAP.PHI.Tangent_Vector) - [GeoDim 1]))==0)
TF = false;
end
end
if ~isempty(myMAP.PHI.Normal_Vector)
if ~(min(abs(size(myMAP.PHI.Normal_Vector) - [GeoDim 1]))==0)
TF = false;
end
end
if ~isempty(myMAP.PHI.Tangent_Space_Projection)
if ~(min(abs(size(myMAP.PHI.Tangent_Space_Projection) - [GeoDim GeoDim]))==0)
TF = false;
end
end
if ~isempty(myMAP.PHI.Hess)
[T1, T2, GD] = size(myMAP.PHI.Hess);
SizeHess = [T1, T2, GD];
if ~(min(abs(SizeHess - [TopDim TopDim GeoDim]))==0)
TF = false;
end
end
if ~isempty(myMAP.PHI.Hess_Inv_Map)
[T1, T2, GD] = size(myMAP.PHI.Hess_Inv_Map);
SizeHessInv = [T1, T2, GD];
if ~(min(abs(SizeHessInv - [TopDim TopDim GeoDim]))==0)
TF = false;
end
end
if ~isempty(myMAP.PHI.Grad_Metric)
[T1, T2, GD] = size(myMAP.PHI.Grad_Metric);
SizeGradMet = [T1, T2, GD];
if ~(min(abs(SizeGradMet - [TopDim TopDim GeoDim]))==0)
TF = false;
end
end
if ~isempty(myMAP.PHI.Grad_Inv_Metric)
[T1, T2, GD] = size(myMAP.PHI.Grad_Inv_Metric);
SizeGradInvMet = [T1, T2, GD];
if ~(min(abs(SizeGradInvMet - [TopDim TopDim GeoDim]))==0)
TF = false;
end
end
if ~isempty(myMAP.PHI.Second_Fund_Form)
if ~(min(abs(size(myMAP.PHI.Second_Fund_Form) - [TopDim TopDim]))==0)
TF = false;
end
if ~(min(abs(size(myMAP.PHI.Det_Second_Fund_Form) - [1 1]))==0)
TF = false;
end
if ~(min(abs(size(myMAP.PHI.Inv_Det_Second_Fund_Form) - [1 1]))==0)
TF = false;
end
end
if ~isempty(myMAP.PHI.Total_Curvature_Vector)
if ~(min(abs(size(myMAP.PHI.Total_Curvature_Vector) - [GeoDim 1]))==0)
TF = false;
end
end
if ~isempty(myMAP.PHI.Total_Curvature)
if ~(min(abs(size(myMAP.PHI.Total_Curvature) - [1 1]))==0)
TF = false;
end
end
if ~isempty(myMAP.PHI.Gauss_Curvature)
if ~(min(abs(size(myMAP.PHI.Gauss_Curvature) - [1 1]))==0)
TF = false;
end
end
if ~isempty(myMAP.PHI.Shape_Operator)
if ~(min(abs(size(myMAP.PHI.Shape_Operator) - [GeoDim GeoDim]))==0)
TF = false;
end
end
% verify code generation!
NB = 3; % check against the use of 3 basis functions!
Map_PHI( 1).Code = myMAP.PHI_Mesh_Size_C_Code(NB);
Map_PHI( 2).Code = myMAP.PHI_Val_C_Code(NB);
Map_PHI( 3).Code = myMAP.PHI_Grad_C_Code(NB);
Map_PHI( 4).Code = myMAP.PHI_Metric_C_Code;
Map_PHI( 5).Code = myMAP.PHI_Det_Metric_C_Code;
Map_PHI( 6).Code = myMAP.PHI_Inv_Det_Metric_C_Code;
Map_PHI( 7).Code = myMAP.PHI_Inv_Metric_C_Code;
Map_PHI( 8).Code = myMAP.PHI_Det_Jac_C_Code;
Map_PHI( 9).Code = myMAP.PHI_Det_Jac_w_Weight_C_Code;
Map_PHI(10).Code = myMAP.PHI_Inv_Det_Jac_C_Code;
Map_PHI(11).Code = myMAP.PHI_Inv_Grad_C_Code;
Map_PHI(12).Code = myMAP.PHI_Tangent_Vector_C_Code;
Map_PHI(13).Code = myMAP.PHI_Normal_Vector_C_Code;
Map_PHI(14).Code = myMAP.PHI_Tan_Space_Proj_C_Code;
Map_PHI(15).Code = myMAP.PHI_Hess_C_Code(NB);
Map_PHI(16).Code = myMAP.PHI_Hess_Inv_Map_C_Code;
Map_PHI(17).Code = myMAP.PHI_Grad_Metric_C_Code;
Map_PHI(18).Code = myMAP.PHI_Grad_Inv_Metric_C_Code;
Map_PHI(19).Code = myMAP.PHI_2nd_Fund_Form_C_Code;
Map_PHI(20).Code = myMAP.PHI_Det_2nd_Fund_Form_C_Code;
Map_PHI(21).Code = myMAP.PHI_Inv_Det_2nd_Fund_Form_C_Code;
Map_PHI(22).Code = myMAP.PHI_Total_Curvature_Vector_C_Code;
Map_PHI(23).Code = myMAP.PHI_Total_Curvature_C_Code;
Map_PHI(24).Code = myMAP.PHI_Gauss_Curvature_C_Code;
Map_PHI(25).Code = myMAP.PHI_Shape_Operator_C_Code;
% disp('-----------------------------------------------');
% GeoDim
% TopDim
% LIN_MAP_TF
% Code1 = myMAP.PHI_Grad_Inv_Metric_C_Code;
% if ~isempty(Code1)
% display_code_snippet(Code1);
% end
% load up reference data
if LIN_MAP_TF
LM_str = 'true';
else
LM_str = 'false';
end
DIR = fileparts(mfilename('fullpath'));
FN_str = ['Map_PHI_Codes_', num2str(GeoDim), num2str(TopDim), '_', LM_str, '_NumBasis_', num2str(NB), '.mat'];
FullFile_string = fullfile(DIR, FN_str);
RefData = load(FullFile_string,'Map_PHI');
% check against reference data
for ind=1:length(Map_PHI(:))
STRUCTS_MATCH = isequal(RefData.Map_PHI(ind),Map_PHI(ind));
if ~STRUCTS_MATCH
TF = false; % test failed!
disp('RefData:');
display_code_snippet(RefData.Map_PHI(ind).Code);
disp('Actual:');
display_code_snippet(Map_PHI(ind).Code);
break;
end
end
end
function display_code_snippet(Code)
Code.Var_Name(1)
Code.Constant
disp('Definition:');
for ii = 1:length(Code.Defn)
disp(Code.Defn(ii).line);
end
disp(' ');
disp('Evaluation:');
for ii = 1:length(Code.Eval_Snip)
disp(Code.Eval_Snip(ii).line);
end
end
|
github
|
eardi/sm-fpca-master
|
test_Hdiv_Trans.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Transformer/Unit_Test/test_Hdiv_Trans.m
| 2,585 |
utf_8
|
b48224497c37a2d9a5f384bfb36b8ff1
|
function status = test_Hdiv_Trans()
%test_Hdiv_Trans
%
% Test code for FELICITY class.
% Copyright (c) 05-19-2016, Shawn W. Walker
status = 0;
GM_test = Geometric_Trans('test',2,2,true);
FUNC1_test = Hdiv_Trans('test',GM_test);
% make sure all the fields are there!
if (min(isfield(FUNC1_test.vv,{'Orientation','Val','Div'}))==0)
status = 1;
end
% check all cases!
% (GeoDim,TopDim)
for gg=2:3
for tt=2:gg
if ~valid_vv_struct(gg,tt,false)
status = 1;
end
if ~valid_vv_struct(gg,tt,true)
status = 1;
end
end
end
%%%%%%%%%%%%%
if (status==0)
disp('Test passed!');
else
disp('Test failed!');
end
end
function TF = valid_vv_struct(GeoDim,TopDim,LIN_MAP_TF)
TF = true; % init test result to passed
% define a map!
myMAP = Geometric_Trans('test',GeoDim,TopDim,LIN_MAP_TF);
myFUNC = Hdiv_Trans('test',myMAP);
% ensure that the symbolic variables have the correct size!
if ~(min(abs(size(myFUNC.vv.Orientation) - [1 1]))==0)
TF = false;
end
if ~isempty(myFUNC.vv.Val)
if ~(min(abs(size(myFUNC.vv.Val) - [GeoDim 1]))==0)
TF = false;
end
end
if ~isempty(myFUNC.vv.Div)
if ~(min(abs(size(myFUNC.vv.Div) - [1 1]))==0)
TF = false;
end
end
% verify code generation!
%Func_vv( 1).Code = myFUNC.FUNC_Orientation_C_Code;
Func_vv( 1).Code = myFUNC.FUNC_Val_C_Code;
Func_vv( 2).Code = myFUNC.FUNC_Div_C_Code;
Func_vv( 3).Code = myFUNC.COEF_FUNC_Val_C_Code;
Func_vv( 4).Code = myFUNC.COEF_FUNC_Div_C_Code;
% load up reference data
if LIN_MAP_TF
LM_str = 'true';
else
LM_str = 'false';
end
DIR = fileparts(mfilename('fullpath'));
FN_str = ['Func_vv_Hdiv_Codes_', num2str(GeoDim), num2str(TopDim), '_', LM_str, '.mat'];
FullFile_string = fullfile(DIR, FN_str);
RefData = load(FullFile_string,'Func_vv');
%save(FullFile_string,'Func_vv');
% for ind = 1:4
% Num_Lines = length(Func_vv(ind).Code);
% for k = 1:Num_Lines
% Func_vv(ind).Code(k).Var_Name
% Func_vv(ind).Code(k).Constant
% for jj = 1:length(Func_vv(ind).Code(k).Defn)
% Func_vv(ind).Code(k).Defn(jj)
% end
% for jj = 1:length(Func_vv(ind).Code(k).Eval_Snip)
% Func_vv(ind).Code(k).Eval_Snip(jj)
% end
% end
% end
% check against reference data
for ind=1:length(Func_vv(:))
STRUCTS_MATCH = isequal(RefData.Func_vv(ind),Func_vv(ind));
if ~STRUCTS_MATCH
TF = false; % test failed!
break;
end
end
end
|
github
|
eardi/sm-fpca-master
|
test_Hcurl_Trans.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Transformer/Unit_Test/test_Hcurl_Trans.m
| 2,870 |
utf_8
|
821f758f3b1246c472446181f738f1bf
|
function status = test_Hcurl_Trans()
%test_Hcurl_Trans
%
% Test code for FELICITY class.
% Copyright (c) 03-24-2018, Shawn W. Walker
status = 0;
GM_test = Geometric_Trans('test',2,2,true);
FUNC1_test = Hcurl_Trans('test',GM_test);
% make sure all the fields are there!
if (min(isfield(FUNC1_test.vv,{'Orientation','Val','Curl'}))==0)
status = 1;
end
% check all cases!
% (GeoDim,TopDim)
for gg=2:3
tt = gg;
disp('SWW: need to implement H(curl) on surfaces...');
%for tt=2:gg
if ~valid_vv_struct(gg,tt,false)
status = 1;
end
if ~valid_vv_struct(gg,tt,true)
status = 1;
end
%end
end
%%%%%%%%%%%%%
if (status==0)
disp('Test passed!');
else
disp('Test failed!');
end
end
function TF = valid_vv_struct(GeoDim,TopDim,LIN_MAP_TF)
TF = true; % init test result to passed
% define a map!
myMAP = Geometric_Trans('test',GeoDim,TopDim,LIN_MAP_TF);
myFUNC = Hcurl_Trans('test',myMAP);
% ensure that the symbolic variables have the correct size!
if ~(min(abs(size(myFUNC.vv.Orientation) - [1 1]))==0)
TF = false;
end
if ~isempty(myFUNC.vv.Val)
if ~(min(abs(size(myFUNC.vv.Val) - [GeoDim 1]))==0)
TF = false;
end
end
if ~isempty(myFUNC.vv.Curl)
if and((TopDim==2),(GeoDim==2))
if ~(min(abs(size(myFUNC.vv.Curl) - [1 1]))==0)
TF = false;
end
elseif and((TopDim==3),(GeoDim==3))
if ~(min(abs(size(myFUNC.vv.Curl) - [GeoDim 1]))==0)
TF = false;
end
end
end
% verify code generation!
%Func_vv( 1).Code = myFUNC.FUNC_Orientation_C_Code;
Func_vv( 1).Code = myFUNC.FUNC_Val_C_Code;
Func_vv( 2).Code = myFUNC.FUNC_Curl_C_Code;
Func_vv( 3).Code = myFUNC.COEF_FUNC_Val_C_Code;
Func_vv( 4).Code = myFUNC.COEF_FUNC_Curl_C_Code;
% load up reference data
if LIN_MAP_TF
LM_str = 'true';
else
LM_str = 'false';
end
DIR = fileparts(mfilename('fullpath'));
FN_str = ['Func_vv_Hcurl_Codes_', num2str(GeoDim), num2str(TopDim), '_', LM_str, '.mat'];
FullFile_string = fullfile(DIR, FN_str);
RefData = load(FullFile_string,'Func_vv');
%save(FullFile_string,'Func_vv');
% for ind = 1:4
% Num_Lines = length(Func_vv(ind).Code);
% for k = 1:Num_Lines
% Func_vv(ind).Code(k).Var_Name
% Func_vv(ind).Code(k).Constant
% for jj = 1:length(Func_vv(ind).Code(k).Defn)
% Func_vv(ind).Code(k).Defn(jj)
% end
% for jj = 1:length(Func_vv(ind).Code(k).Eval_Snip)
% Func_vv(ind).Code(k).Eval_Snip(jj)
% end
% end
% end
% check against reference data
for ind=1:length(Func_vv(:))
STRUCTS_MATCH = isequal(RefData.Func_vv(ind),Func_vv(ind));
if ~STRUCTS_MATCH
TF = false; % test failed!
break;
end
end
end
|
github
|
eardi/sm-fpca-master
|
Write_C_Code_To_File.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Transformer/@generic_trans/Write_C_Code_To_File.m
| 1,494 |
utf_8
|
de3f56aac42961fe0a8887fc6b98d99a
|
function status = Write_C_Code_To_File(obj,FileName,Struct_C_Code)
%Write_C_Code_To_File
%
% This writes a given code struct and writes it to a given file.
% Copyright (c) 02-20-2012, Shawn W. Walker
% open file for writing
fid = fopen(FileName, 'w');
if ~isempty(Struct_C_Code)
% write the variable names
write_code_line(fid,'// Variable Names:');
write_code_line(fid,'// -----------------------');
for ind=1:length(Struct_C_Code.Var_Name(:))
write_code_line(fid, Struct_C_Code.Var_Name(ind).line);
end
write_CR(fid);
% write the definition code
write_code_line(fid,'// Definition Code:');
write_code_line(fid,'// ------------------------');
for ind=1:length(Struct_C_Code.Defn)
write_code_line(fid, Struct_C_Code.Defn(ind).line);
end
write_CR(fid);
% write the evaluation code
write_code_line(fid,'// Evaluation Code:');
write_code_line(fid,'// ------------------------');
for ind=1:length(Struct_C_Code.Eval_Snip)
write_code_line(fid, Struct_C_Code.Eval_Snip(ind).line);
end
write_CR(fid);
else
write_code_line(fid,'// EMPTY!!!!!!!!');
write_CR(fid);
end
% DONE!
status = fclose(fid);
end
function status = write_code_line(fid,STR)
ENDL = '\n';
if ~isempty(STR)
status = fprintf(fid, [STR, ENDL]);
end
end
function status = write_CR(fid)
ENDL = '\n';
status = fprintf(fid, ['', ENDL]);
end
|
github
|
eardi/sm-fpca-master
|
Output_CPP_Eval_Extension.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Transformer/@Hdiv_Trans/Output_CPP_Eval_Extension.m
| 1,235 |
utf_8
|
5996ca59e64c741048bc8a4d432f8b70
|
function CPP_Eval = Output_CPP_Eval_Extension(obj,FIELD_str,Components)
%Output_CPP_Eval_Extension
%
% This outputs a string representing the C++ evaluation code for the given
% variable name.
%
% Components = [basis_comp_1, basis_comp_2, comp_1, comp_2, etc...]
% Copyright (c) 03-25-2012, Shawn W. Walker
% peel off the basis component
Basis_Comp = Components(1:2);
Components = Components(3:end);
if strcmp(FIELD_str,'Orientation')
error('you don''t need this!');
elseif strcmp(FIELD_str,'Val')
Vec_Comp_C_index_STR = Get_Index_String(Basis_Comp(1));
CPP_Eval = ['.v', Vec_Comp_C_index_STR];
elseif strcmp(FIELD_str,'Div')
CPP_Eval = ['.a', ''];
% elseif strcmp(FIELD_str,'Grad')
% Grad_Comp_C_index_STR = Get_Index_String(Components(1));
% CPP_Eval = ['.v', Grad_Comp_C_index_STR];
% elseif strcmp(FIELD_str,'Hess')
% Comp_1_C_index_STR = Get_Index_String(Components(1));
% Comp_2_C_index_STR = Get_Index_String(Components(2));
% CPP_Eval = ['.m', Comp_1_C_index_STR, Comp_2_C_index_STR];
else
error('Not valid!');
end
end
function INDEX_str = Get_Index_String(Index)
% use C-style indexing
INDEX_str = ['[', num2str(Index - 1), ']'];
end
|
github
|
eardi/sm-fpca-master
|
Premap_Basis.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Transformer/@Hdiv_Trans/private/Premap_Basis.m
| 1,747 |
utf_8
|
5bb82ea1bf4671cec699d718a1afe095
|
function Sign_Change = Premap_Basis(Mesh_Orient,All_Facet_DoFs,Num_Basis)
%Premap_Basis
%
% This is used by the H(div) elements for pre-mapping basis functions to
% adjust for different facet orientations.
%
% Sign_Change = Premap_Basis_Hdiv(Mesh_Orient,All_Facet_DoFs,Num_Basis);
%
% Mesh_Orient: NxF vector indicating actual orientation of mesh elements
% (N is the number of elements; F is the number of element
% facets.)
% Ex: [+1, -1, +1; ...] (F = 3 here)
% Elem #1: facet 1 and facet 3 are positively oriented;
% facet 2 is negative, etc...
% All_Facet_DoFs: cell array of sets of DoFs attached to all facets.
% Num_Basis: number of basis functions in the element.
%
% Sign_Change: NxB matrix, where B = number of basis functions:
% +1 = no sign change.
% -1 = flip sign of corresponding basis function.
% Rows correspond to rows of "Mesh_Orient".
% Copyright (c) 09-12-2016, Shawn W. Walker
Num_Elem = size(Mesh_Orient,1);
Num_Facets = size(Mesh_Orient,2);
Sign_Change = ones(Num_Elem,Num_Basis); % init
% loop through the local facets (edges) of the mesh elements
for fi = 1:Num_Facets
Facet_Sign = Mesh_Orient(:,fi);
Neg_Mask = (Facet_Sign==-1);
% gets DoF indices on the current facet
DoFs_On_Facet = get_dofs_on_facet(All_Facet_DoFs,fi);
% flip necessary signs
Sign_Change(Neg_Mask,DoFs_On_Facet) = -1;
end
end
function DoFs = get_dofs_on_facet(All_Facet_DoFs,Facet_Index)
DoFs = []; % init
for ci = 1:length(All_Facet_DoFs)
DoF_Set = All_Facet_DoFs{ci};
DI = DoF_Set(Facet_Index,:);
DoFs = [DoFs; DI(:)];
end
end
|
github
|
eardi/sm-fpca-master
|
Generate_Local_Maps_For_Geometric_Basis_Functions.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Transformer/@Codim_Map/Generate_Local_Maps_For_Geometric_Basis_Functions.m
| 10,246 |
utf_8
|
82e826bc3b9ccb1863c1f11985f48ba0
|
function Local_Map = Generate_Local_Maps_For_Geometric_Basis_Functions(obj,entity_ind)
%Generate_Local_Maps_For_Geometric_Basis_Functions
%
% This generates two symbolic maps (expressions) for generating geometric
% basis functions that are reduced to Subdomains and Domains of Integration
% (DoI's).
%
% Local_Map = obj.Generate_Local_Maps_For_Geometric_Basis_Functions(ent);
%
% ent = local mesh topological entity index; either a 1 or 2 length vector of
% local indices; 2 length case is a special case.
%
% Local_Map = struct containing the two maps:
% .Sub = FELSymFunc object that defines a map from the reference
% element of the Subdomain to a given topological entity in
% the Global cell (same topological dimension as the
% Subdomain, but the geometric dimension may be higher).
% .DoI = FELSymFunc object; similar, except it maps from the
% reference element of the DoI to a topological entity in
% the Subdomain cell.
%
% The map Local_Map.Sub has range in the Global cell reference element, and
% domain is the Subdomain cell reference element.
%
% The map Local_Map.DoI has range in the Subdomain cell reference element, and
% domain is the DoI cell reference element.
%
% Thus, the two maps can be composed to create a new map that goes from the
% DoI to the Global cell reference element.
%
% Sub Top_Dim | independent variable
% 1 | u_hat
% 2 | u_hat,v_hat
% 3 | u_hat,v_hat,w_hat
%
% DoI Top_Dim | independent variable
% 1 | x_hat
% 2 | x_hat,y_hat
% 3 | x_hat,y_hat,z_hat
% Copyright (c) 05-20-2016, Shawn W. Walker
Global_Hold_All_Top_Dim = obj.Domain.Global.Top_Dim;
Subdomain_Top_Dim = obj.Domain.Subdomain.Top_Dim;
DoI_Top_Dim = obj.Domain.Integration_Domain.Top_Dim;
% Note: 3 >= Global_Hold_All_Top_Dim >= Subdomain_Top_Dim >= DoI_Top_Dim >= 1
% define symbolic variables
u = sym('u_hat');
v = sym('v_hat');
w = sym('w_hat');
x = sym('x_hat');
y = sym('y_hat');
z = sym('z_hat');
if (Global_Hold_All_Top_Dim==1)
% only get the identity
if (Subdomain_Top_Dim==1)
Sub_Sym_Map = u; % identity map
if (DoI_Top_Dim==1) % codim = 0
DoI_Sym_Map = x; % identity map
else
error('Invalid!');
end
else
error('Invalid!');
end
elseif (Global_Hold_All_Top_Dim==2)
if (Subdomain_Top_Dim==2) % codim = 0
Sub_Sym_Map = [u;v]; % identity map
if (DoI_Top_Dim==2)
DoI_Sym_Map = [x;y]; % identity map
elseif (DoI_Top_Dim==1) % codim = 1
DoI_Sym_Map = map_unit_interval_to_tri_edge(x,entity_ind(1));
else
error('Invalid!');
end
elseif (Subdomain_Top_Dim==1)
Sub_Sym_Map = map_unit_interval_to_tri_edge(u,entity_ind(1));
if (DoI_Top_Dim==1) % codim = 1
DoI_Sym_Map = x; % identity map
else
error('Invalid!');
end
else
error('Invalid!');
end
elseif (Global_Hold_All_Top_Dim==3)
if (Subdomain_Top_Dim==3)
Sub_Sym_Map = [u;v;w]; % identity map
if (DoI_Top_Dim==3) % codim = 0
DoI_Sym_Map = [x;y;z]; % identity map
elseif (DoI_Top_Dim==2) % codim = 1
DoI_Sym_Map = map_unit_triangle_to_tet_face([x;y],entity_ind(1));
elseif (DoI_Top_Dim==1) % codim = 2
DoI_Sym_Map = map_unit_interval_to_tet_edge(x,entity_ind(1));
else
error('Invalid!');
end
elseif (Subdomain_Top_Dim==2)
Sub_Sym_Map = map_unit_triangle_to_tet_face([u;v],entity_ind(1));
if (DoI_Top_Dim==2) % codim = 1
DoI_Sym_Map = [x;y]; % identity map
elseif (DoI_Top_Dim==1) % codim = 2
% if this is the special case, then we want the second entity index
DoI_Sym_Map = map_unit_interval_to_tri_edge(x,entity_ind(end));
else
error('Invalid!');
end
elseif (Subdomain_Top_Dim==1)
Sub_Sym_Map = map_unit_interval_to_tet_edge(u,entity_ind(1));
if (DoI_Top_Dim==1) % codim = 2
DoI_Sym_Map = x; % identity map
else
error('Invalid!');
end
else
error('Invalid!');
end
else
error('Invalid!');
end
if (Subdomain_Top_Dim==1)
Sub_Vars = {'u_hat'};
elseif (Subdomain_Top_Dim==2)
Sub_Vars = {'u_hat', 'v_hat'};
elseif (Subdomain_Top_Dim==3)
Sub_Vars = {'u_hat', 'v_hat', 'w_hat'};
else
error('Invalid!');
end
Local_Map.Sub = FELSymFunc(Sub_Sym_Map,Sub_Vars);
if (DoI_Top_Dim==1)
DoI_Vars = {'x_hat'};
elseif (DoI_Top_Dim==2)
DoI_Vars = {'x_hat', 'y_hat'};
elseif (DoI_Top_Dim==3)
DoI_Vars = {'x_hat', 'y_hat', 'z_hat'};
else
error('Invalid!');
end
Local_Map.DoI = FELSymFunc(DoI_Sym_Map,DoI_Vars);
end
function Sym_Map = map_unit_interval_to_tri_edge(indep_var,Entity_Index)
% vertices of the reference triangle
A1 = [0; 0];
A2 = [1; 0];
A3 = [0; 1];
% map quad rule from interval to 1 of 3 edges with orientation
if (Entity_Index==1) % edge1, pos
p1 = A2;
p2 = A3;
elseif (Entity_Index==2) % edge2, pos
p1 = A3;
p2 = A1;
elseif (Entity_Index==3) % edge3, pos
p1 = A1;
p2 = A2;
elseif (Entity_Index==-1) % edge1, neg
p1 = A3;
p2 = A2;
elseif (Entity_Index==-2) % edge2, neg
p1 = A1;
p2 = A3;
elseif (Entity_Index==-3) % edge3, neg
p1 = A2;
p2 = A1;
else
error('Entity_Index outside valid range!');
end
% Map = (1 - t) * p1 + t*p2
Sym_Map = (1 - indep_var) * p1 + indep_var * p2;
end
function Sym_Map = map_unit_interval_to_tet_edge(indep_var,Entity_Index)
% vertices of the reference tetrahedron
A1 = [0; 0; 0];
A2 = [1; 0; 0];
A3 = [0; 1; 0];
A4 = [0; 0; 1];
% map quad rule from interval to 1 of 6 edges with orientation
if (Entity_Index==1) % edge1, pos
p1 = A1;
p2 = A2;
elseif (Entity_Index==2) % edge2, pos
p1 = A1;
p2 = A3;
elseif (Entity_Index==3) % edge3, pos
p1 = A1;
p2 = A4;
elseif (Entity_Index==4) % edge4, pos
p1 = A2;
p2 = A3;
elseif (Entity_Index==5) % edge5, pos
p1 = A3;
p2 = A4;
elseif (Entity_Index==6) % edge6, pos
p1 = A4;
p2 = A2;
elseif (Entity_Index==-1) % edge1, neg
p1 = A2;
p2 = A1;
elseif (Entity_Index==-2) % edge2, neg
p1 = A3;
p2 = A1;
elseif (Entity_Index==-3) % edge3, neg
p1 = A4;
p2 = A1;
elseif (Entity_Index==-4) % edge4, neg
p1 = A3;
p2 = A2;
elseif (Entity_Index==-5) % edge5, neg
p1 = A4;
p2 = A3;
elseif (Entity_Index==-6) % edge6, neg
p1 = A2;
p2 = A4;
else
error('Entity_Index outside valid range!');
end
% Map = (1 - t) * p1 + t*p2
Sym_Map = (1 - indep_var) * p1 + indep_var * p2;
end
function Sym_Map = map_unit_triangle_to_tet_face(indep_var,Entity_Index)
% vertices of the reference tetrahedron
A1 = [0; 0; 0];
A2 = [1; 0; 0];
A3 = [0; 1; 0];
A4 = [0; 0; 1];
% map quad rule from ref triangle to 1 of 4 faces with orientation
if (Entity_Index==1) % face1, pos
v1 = A2;
v2 = A3;
v3 = A4;
elseif (Entity_Index==2) % face2, pos
v1 = A1;
v2 = A4;
v3 = A3;
elseif (Entity_Index==3) % face3, pos
v1 = A1;
v2 = A2;
v3 = A4;
elseif (Entity_Index==4) % face4, pos
v1 = A1;
v2 = A3;
v3 = A2;
elseif (Entity_Index==-1) % face1, neg
v1 = A2; % pivot
v2 = A4;
v3 = A3;
elseif (Entity_Index==-2) % face2, neg
v1 = A1; % pivot
v2 = A3;
v3 = A4;
elseif (Entity_Index==-3) % face3, neg
v1 = A1; % pivot
v2 = A4;
v3 = A2;
elseif (Entity_Index==-4) % face4, neg
v1 = A1; % pivot
v2 = A2;
v3 = A3;
else
error('Entity_Index outside valid range!');
end
% Map = (1 - r - s) * v1 + r*v2 + s*v3
Sym_Map = (1 - indep_var(1) - indep_var(2)) * v1 +...
indep_var(1) * v2 +...
indep_var(2) * v3;
%
end
% function Sym_Map = map_unit_interval_to_tet_face_edge(indep_var,Entity_Index)
%
% Sub_Entity_Index = Entity_Index(1);
% DoI_Entity_Index = Entity_Index(2);
%
% % vertices of the reference tetrahedron
% A1 = [0; 0; 0];
% A2 = [1; 0; 0];
% A3 = [0; 1; 0];
% A4 = [0; 0; 1];
%
% % first get the local face with orientation
% if (Sub_Entity_Index==1) % face1, pos
% v1 = A2;
% v2 = A3;
% v3 = A4;
% elseif (Sub_Entity_Index==2) % face2, pos
% v1 = A1;
% v2 = A4;
% v3 = A3;
% elseif (Sub_Entity_Index==3) % face3, pos
% v1 = A1;
% v2 = A2;
% v3 = A4;
% elseif (Sub_Entity_Index==4) % face4, pos
% v1 = A1;
% v2 = A3;
% v3 = A2;
% elseif (Sub_Entity_Index==-1) % face1, neg
% v1 = A2; % pivot
% v2 = A4;
% v3 = A3;
% elseif (Sub_Entity_Index==-2) % face2, neg
% v1 = A1; % pivot
% v2 = A3;
% v3 = A4;
% elseif (Sub_Entity_Index==-3) % face3, neg
% v1 = A1; % pivot
% v2 = A4;
% v3 = A2;
% elseif (Sub_Entity_Index==-4) % face4, neg
% v1 = A1; % pivot
% v2 = A2;
% v3 = A3;
% else
% error('Sub_Entity_Index outside valid range!');
% end
%
% % Now, get the local edge (of the local face) with orientation
% if (DoI_Entity_Index==1) % edge1, pos
% p1 = v2;
% p2 = v3;
% elseif (DoI_Entity_Index==2) % edge2, pos
% p1 = v3;
% p2 = v1;
% elseif (DoI_Entity_Index==3) % edge3, pos
% p1 = v1;
% p2 = v2;
% elseif (DoI_Entity_Index==-1) % edge1, neg
% p1 = v3;
% p2 = v2;
% elseif (DoI_Entity_Index==-2) % edge2, neg
% p1 = v1;
% p2 = v3;
% elseif (DoI_Entity_Index==-3) % edge3, neg
% p1 = v2;
% p2 = v1;
% else
% error('DoI_Entity_Index outside valid range!');
% end
%
% % Map = (1 - t) * p1 + t*p2
% Sym_Map = (1 - indep_var) * p1 + indep_var * p2;
%
% end
|
github
|
eardi/sm-fpca-master
|
PHI_Grad_Metric_C_Code.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Transformer/@Geometric_Trans/PHI_Grad_Metric_C_Code.m
| 6,314 |
utf_8
|
842ef98e2fd16bbfefd4f9b326c1cc7b
|
function CODE = PHI_Grad_Metric_C_Code(obj)
%PHI_Grad_Metric_C_Code
%
% Generate C-code for direct evaluation of PHI.Grad_Metric.
% PHI_Grad_Metric_r_ij(qp) =
% \partial_r SUM^GeoDim_{k=1} PHI_Grad_ki(qp) * PHI_Grad_kj(qp),
% 1 <= i,j <= TopDim,
% and qp are the coordinates of a quadrature point.
% Copyright (c) 08-11-2014, Shawn W. Walker
if ~isempty(obj.PHI.Grad_Metric) % if this concept exists!
% make var string
CODE.Var_Name(1).line = []; % init
CODE.Var_Name(1).line = obj.Output_CPP_Var_Name('Grad_Metric');
% make a reference for the data evaluated at a quad point
CPP_REF_Var_str = obj.Get_Quad_Pt_CPP_Ref_Var_Name(CODE.Var_Name(1).line);
% evaluate at the given tensor entry index
PHI_Grad_Metric_Tensor_str = [CPP_REF_Var_str];
% need the gradient of the map!
Map_PHI_Grad_str = obj.Output_CPP_Var_Name('Grad');
Map_PHI_Grad_Matrix_str = [Map_PHI_Grad_str, '[qp_i]'];
% need the hessian of the map!
Map_PHI_Hess_str = obj.Output_CPP_Var_Name('Hess');
Map_PHI_Hess_Tensor_str = [Map_PHI_Hess_str, '[qp_i]'];
GD = obj.GeoDim;
CONST_Metric = obj.Lin_PHI_TF;
if ~CONST_Metric % metric is not constant
% evaluate!
if (obj.TopDim==1)
EVAL_STR(3).line = []; % init
EVAL_STR(1).line = '// compute 2 * d^2/ds^2 vX DOT d/ds vX';
DP_str = get_dot_product_str(GD,Map_PHI_Hess_Tensor_str,Map_PHI_Grad_Matrix_str,1,1,1);
EVAL_STR(2).line = ['const double HG_DP = ', DP_str, ';'];
LHS = get_grad_metric_eval_str(PHI_Grad_Metric_Tensor_str,1,1,1);
EVAL_STR(3).line = [LHS, ' = 2.0 * HG_DP;'];
elseif (obj.TopDim==2)
EVAL_STR(16).line = []; % init
EVAL_STR(1).line = '// compute d/ds_r d/ds_i vX DOT d/ds_j vX + d/ds_r d/ds_j vX DOT d/ds_i vX';
EVAL_STR(2).line = 'double HG_DP_A;';
% component: 1,1,1
DP_str = get_dot_product_str(GD,Map_PHI_Hess_Tensor_str,Map_PHI_Grad_Matrix_str,1,1,1);
EVAL_STR(3).line = ['HG_DP_A = ', DP_str, ';'];
LHS_111 = get_grad_metric_eval_str(PHI_Grad_Metric_Tensor_str,1,1,1);
EVAL_STR(4).line = [LHS_111, ' = 2.0 * HG_DP_A;'];
% component: 1,2,2
DP_str = get_dot_product_str(GD,Map_PHI_Hess_Tensor_str,Map_PHI_Grad_Matrix_str,1,2,2);
EVAL_STR(5).line = ['HG_DP_A = ', DP_str, ';'];
LHS_122 = get_grad_metric_eval_str(PHI_Grad_Metric_Tensor_str,1,2,2);
EVAL_STR(6).line = [LHS_122, ' = 2.0 * HG_DP_A;'];
% component: 2,1,1
DP_str = get_dot_product_str(GD,Map_PHI_Hess_Tensor_str,Map_PHI_Grad_Matrix_str,2,1,1);
EVAL_STR(7).line = ['HG_DP_A = ', DP_str, ';'];
LHS_211 = get_grad_metric_eval_str(PHI_Grad_Metric_Tensor_str,2,1,1);
EVAL_STR(8).line = [LHS_211, ' = 2.0 * HG_DP_A;'];
% component: 2,2,2
DP_str = get_dot_product_str(GD,Map_PHI_Hess_Tensor_str,Map_PHI_Grad_Matrix_str,2,2,2);
EVAL_STR(9).line = ['HG_DP_A = ', DP_str, ';'];
LHS_222 = get_grad_metric_eval_str(PHI_Grad_Metric_Tensor_str,2,2,2);
EVAL_STR(10).line = [LHS_222, ' = 2.0 * HG_DP_A;'];
% component: 1,1,2
DP_str = get_dot_product_str(GD,Map_PHI_Hess_Tensor_str,Map_PHI_Grad_Matrix_str,1,1,2);
EVAL_STR(11).line = ['HG_DP_A = ', DP_str, ';'];
LHS_112 = get_grad_metric_eval_str(PHI_Grad_Metric_Tensor_str,1,1,2);
EVAL_STR(12).line = [LHS_112, ' = HG_DP_A + ', '0.5*', LHS_211, '; // reuse!'];
% component: 1,2,1
LHS_121 = get_grad_metric_eval_str(PHI_Grad_Metric_Tensor_str,1,2,1);
EVAL_STR(13).line = [LHS_121, ' = ', LHS_112, '; // symmetric'];
% component: 2,2,1
DP_str = get_dot_product_str(GD,Map_PHI_Hess_Tensor_str,Map_PHI_Grad_Matrix_str,2,2,1);
EVAL_STR(14).line = ['HG_DP_A = ', DP_str, ';'];
LHS_221 = get_grad_metric_eval_str(PHI_Grad_Metric_Tensor_str,2,2,1);
EVAL_STR(15).line = [LHS_221, ' = HG_DP_A + ', '0.5*', LHS_122, '; // reuse!'];
% component: 2,1,2
LHS_212 = get_grad_metric_eval_str(PHI_Grad_Metric_Tensor_str,2,1,2);
EVAL_STR(16).line = [LHS_212, ' = ', LHS_221, '; // symmetric'];
else
error('Invalid!');
end
else
% map is linear, so metric is constant
EVAL_STR(1).line = [PHI_Grad_Metric_Tensor_str, '.Set_To_Zero(); // metric is constant, so gradient is zero'];
end
% define the data type
SIZE = size(obj.PHI.Grad_Metric,1);
TYPE_str = obj.Get_CPP_Tensor_Data_Type_Name(SIZE,SIZE,SIZE);
Defn_Hdr = '// gradient (in local coordinates) of the metric tensor of the map';
Loop_Hdr = '// compute gradient of metric tensor';
Loop_Comment = [];
CONST_VAR = obj.Lin_PHI_TF;
CODE = obj.create_declaration_and_eval_code(CODE.Var_Name,TYPE_str,EVAL_STR,...
Defn_Hdr,Loop_Hdr,Loop_Comment,CONST_VAR);
else
CODE = [];
end
end
function DP_str = get_dot_product_str(GD,Map_PHI_Hess_Tensor_str,Map_PHI_Grad_Matrix_str,r,i,j)
r_str = ['[', num2str(r-1), ']'];
i_str = ['[', num2str(i-1), ']'];
j_str = ['[', num2str(j-1), ']'];
DP0_str = [Map_PHI_Hess_Tensor_str, '.m[0]', r_str, i_str, ' * ', Map_PHI_Grad_Matrix_str, '.m[0]', j_str];
DP1_str = [Map_PHI_Hess_Tensor_str, '.m[1]', r_str, i_str, ' * ', Map_PHI_Grad_Matrix_str, '.m[1]', j_str];
DP2_str = [Map_PHI_Hess_Tensor_str, '.m[2]', r_str, i_str, ' * ', Map_PHI_Grad_Matrix_str, '.m[2]', j_str];
if (GD==1)
DP_str = DP0_str;
elseif (GD==2)
DP_str = [DP0_str, ' + ', DP1_str];
elseif (GD==3)
DP_str = [DP0_str, ' + ', DP1_str, ' + ', DP2_str];
else
error('Invalid!');
end
end
function STR = get_grad_metric_eval_str(PHI_Grad_Metric_Tensor_str,r,i,j)
r_str = ['[', num2str(r-1), ']'];
i_str = ['[', num2str(i-1), ']'];
j_str = ['[', num2str(j-1), ']'];
STR = [PHI_Grad_Metric_Tensor_str, '.m', r_str, i_str, j_str];
end
|
github
|
eardi/sm-fpca-master
|
PHI_Mesh_Size_C_Code.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Transformer/@Geometric_Trans/PHI_Mesh_Size_C_Code.m
| 5,483 |
utf_8
|
a49c6e600dcd44d9f5f9968ad9a61e09
|
function CODE = PHI_Mesh_Size_C_Code(obj,Num_Basis)
%PHI_Mesh_Size_C_Code
%
% Generate C-code for computing the mesh size (with PHI).
% vx_i(qp) = SUM^{Num_Basis}_{k=1} c_{ki} phi_k(\hat{vx}_i),
% 1 <= i <= GeoDim, and \hat{vx}_i are the local
% coordinates of the reference element (simplex).
% Copyright (c) 08-17-2017, Shawn W. Walker
% make var string
CODE.Var_Name(1).line = []; % init
CODE.Var_Name(1).line = obj.Output_CPP_Var_Name('Mesh_Size');
% loop thru all components of the map
Num_Corner_Vtx = obj.TopDim + 1;
EVAL_STR(obj.GeoDim*Num_Corner_Vtx + Num_Corner_Vtx + 2).line = []; % init
Vec_Data_Type_str = obj.Get_CPP_Vector_Data_Type_Name(obj.GeoDim);
INDEX = 0;
for cp=1:Num_Corner_Vtx
INDEX = INDEX + 1;
EVAL_STR(INDEX).line = [Vec_Data_Type_str, ' ', 'Pt', num2str(cp), ';'];
end
INDEX = INDEX + 1;
EVAL_STR(INDEX).line = '// compute vertex positions by summing over basis functions';
for ig=1:obj.GeoDim
for cp=1:Num_Corner_Vtx
INDEX = INDEX + 1;
EVAL_STR(INDEX).line = gen_eval_code(obj,Num_Basis,ig,cp);
end
end
% compute the mesh size
INDEX = INDEX + 1;
EVAL_STR(INDEX).line = '// compute the local mesh size';
Num1 = length(EVAL_STR);
if (obj.TopDim==1)
EVAL_STR(Num1 + 1).line = [Vec_Data_Type_str, ' ', 'TEMP_Vec' ';'];
EVAL_STR(Num1 + 2).line = ['Subtract_Vector(Pt2, Pt1, TEMP_Vec);'];
EVAL_STR(Num1 + 3).line = [CODE.Var_Name(1).line, '[0].a', ' = l2_norm(TEMP_Vec);'];
elseif (obj.TopDim==2)
EVAL_STR(Num1 + 1).line = [Vec_Data_Type_str, ' ', 'TEMP_Vec' ';'];
EVAL_STR(Num1 + 2).line = ['double MESH_H[3];'];
EVAL_STR(Num1 + 3).line = ['Subtract_Vector(Pt2, Pt1, TEMP_Vec);'];
EVAL_STR(Num1 + 4).line = ['MESH_H[0] = l2_norm(TEMP_Vec);'];
EVAL_STR(Num1 + 5).line = ['Subtract_Vector(Pt3, Pt1, TEMP_Vec);'];
EVAL_STR(Num1 + 6).line = ['MESH_H[1] = l2_norm(TEMP_Vec);'];
EVAL_STR(Num1 + 7).line = ['Subtract_Vector(Pt3, Pt2, TEMP_Vec);'];
EVAL_STR(Num1 + 8).line = ['MESH_H[2] = l2_norm(TEMP_Vec);'];
EVAL_STR(Num1 + 9).line = [CODE.Var_Name(1).line, '[0].a', ' = *max_element(MESH_H, MESH_H+3); // longest edge'];
elseif (obj.TopDim==3)
EVAL_STR(Num1 + 1).line = [Vec_Data_Type_str, ' ', 'TEMP_Vec' ';'];
EVAL_STR(Num1 + 2).line = ['double MESH_H[6];'];
EVAL_STR(Num1 + 3).line = ['Subtract_Vector(Pt2, Pt1, TEMP_Vec);'];
EVAL_STR(Num1 + 4).line = ['MESH_H[0] = l2_norm(TEMP_Vec);'];
EVAL_STR(Num1 + 5).line = ['Subtract_Vector(Pt3, Pt1, TEMP_Vec);'];
EVAL_STR(Num1 + 6).line = ['MESH_H[1] = l2_norm(TEMP_Vec);'];
EVAL_STR(Num1 + 7).line = ['Subtract_Vector(Pt4, Pt1, TEMP_Vec);'];
EVAL_STR(Num1 + 8).line = ['MESH_H[2] = l2_norm(TEMP_Vec);'];
EVAL_STR(Num1 + 9).line = ['Subtract_Vector(Pt3, Pt2, TEMP_Vec);'];
EVAL_STR(Num1 + 10).line = ['MESH_H[3] = l2_norm(TEMP_Vec);'];
EVAL_STR(Num1 + 11).line = ['Subtract_Vector(Pt4, Pt3, TEMP_Vec);'];
EVAL_STR(Num1 + 12).line = ['MESH_H[4] = l2_norm(TEMP_Vec);'];
EVAL_STR(Num1 + 13).line = ['Subtract_Vector(Pt2, Pt4, TEMP_Vec);'];
EVAL_STR(Num1 + 14).line = ['MESH_H[5] = l2_norm(TEMP_Vec);'];
EVAL_STR(Num1 + 15).line = [CODE.Var_Name(1).line, '[0].a', ' = *max_element(MESH_H, MESH_H+6); // longest edge'];
else
error('Invalid!');
end
EVAL_STR(end+1).line = '';
% define the data type
TYPE_str = obj.Get_CPP_Scalar_Data_Type_Name;
Defn_Hdr = '// local mesh size of reference element';
CONST_VAR = true; % the mesh size is constant over each element
CODE = special_declaration_and_eval_code(CODE.Var_Name,TYPE_str,EVAL_STR,...
Defn_Hdr,CONST_VAR);
%
end
function STR = gen_eval_code(obj,Num_Basis,ig,cp)
% constants that multiply the basis functions
coefs = sym('coef_%d_%d_',[Num_Basis, obj.GeoDim]);
local_basis = sym('Geo_phi_%d_',[Num_Basis, 1]);
RESULT = sum(coefs(:,ig) .* local_basis); % evaluate PHI_i(qp)
TEMP_STR = ccode(RESULT); % turn into C-code!
% make string replacements
COORD_str_X = ['Pt', num2str(cp), '.v', '[', num2str(ig-1), ']'];
TEMP_STR = regexprep(TEMP_STR, ' t0', COORD_str_X); % t0 is the default LHS term
for ib=1:Num_Basis
Geo_phi_S_str = ['Geo_phi_', num2str(ib), '_'];
Geo_phi_C_str = ['Geo_Vtx_Basis_Val_0_0_0', '[', num2str(cp-1), ']', '[', num2str(ib-1), ']']; % C-style indexing
TEMP_STR = regexprep(TEMP_STR, Geo_phi_S_str, Geo_phi_C_str);
coef_S_str = ['coef_', num2str(ib), '_', num2str(ig), '_'];
coef_C_str = ['Node_Value', '[', num2str(ig-1), ']', '[kc[', num2str(ib-1), ']]']; % C-style indexing
TEMP_STR = regexprep(TEMP_STR, coef_S_str, coef_C_str);
end
STR = TEMP_STR;
end
function CODE = special_declaration_and_eval_code(Var_Str,TYPE_str,Eval_Str,...
Defn_Hdr,CONST_TF)
% create struct (init)
CODE.Var_Name = Var_Str;
CODE.Constant = CONST_TF; % is the variable a constant (does not vary over the quad points)
CODE.Defn = [];
CODE.Eval_Snip = [];
% create declaration code
CODE.Defn(2).line = [];
CODE.Defn(1).line = Defn_Hdr;
CODE.Defn(2).line = [TYPE_str, ' ', CODE.Var_Name(1).line, '[1]', ';'];
% create evaluation code
num_eval = length(Eval_Str(:));
CODE.Eval_Snip(num_eval).line = [];
for ind=1:num_eval
CODE.Eval_Snip(ind).line = [Eval_Str(ind).line];
end
end
|
github
|
eardi/sm-fpca-master
|
PHI_Hess_C_Code.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Transformer/@Geometric_Trans/PHI_Hess_C_Code.m
| 5,092 |
utf_8
|
d615f7eacfceaab422cac4290afa9022
|
function CODE = PHI_Hess_C_Code(obj,Num_Basis)
%PHI_Hess_C_Code
%
% Generate C-code for direct evaluation of PHI.Hess.
% PHI_Hess_ijk(qp) = SUM^{Num_Basis}_{q=1} c_{qk} *
% \partial_i \partial_j phi_k(qp),
% 1 <= k <= GeoDim, 1 <= i,j <= TopDim
% and qp are the coordinates of a quadrature point.
% Copyright (c) 02-20-2012, Shawn W. Walker
% make var string
CODE.Var_Name(1).line = []; % init
CODE.Var_Name(1).line = obj.Output_CPP_Var_Name('Hess');
if ~obj.Lin_PHI_TF % map is non-linear
% init (part of) output struct
EVAL_STR(obj.TopDim*obj.TopDim*obj.GeoDim).line = []; % init
for kk=1:obj.GeoDim
if (obj.TopDim==1)
% write evaluation code
EVAL_STR(1 + (kk-1)*obj.TopDim^2).line =...
Generate_Evaluation_String(obj,CODE.Var_Name(1).line,1,1,kk,Num_Basis);
elseif (obj.TopDim==2)
% write evaluation code
EVAL_STR(1 + (kk-1)*obj.TopDim^2).line = Generate_Evaluation_String(obj,CODE.Var_Name(1).line,1,1,kk,Num_Basis);
EVAL_STR(2 + (kk-1)*obj.TopDim^2).line = Generate_Evaluation_String(obj,CODE.Var_Name(1).line,1,2,kk,Num_Basis);
EVAL_STR(3 + (kk-1)*obj.TopDim^2).line =...
[obj.Get_CPP_Tensor_Eval_String(CODE.Var_Name(1).line,kk,2,1), ' = ',...
obj.Get_CPP_Tensor_Eval_String(CODE.Var_Name(1).line,kk,1,2), '; // symmetry!'];
EVAL_STR(4 + (kk-1)*obj.TopDim^2).line = Generate_Evaluation_String(obj,CODE.Var_Name(1).line,2,2,kk,Num_Basis);
elseif (obj.TopDim==3)
% write evaluation code
EVAL_STR(1 + (kk-1)*obj.TopDim^2).line = Generate_Evaluation_String(obj,CODE.Var_Name(1).line,1,1,kk,Num_Basis);
EVAL_STR(2 + (kk-1)*obj.TopDim^2).line = Generate_Evaluation_String(obj,CODE.Var_Name(1).line,1,2,kk,Num_Basis);
EVAL_STR(3 + (kk-1)*obj.TopDim^2).line = Generate_Evaluation_String(obj,CODE.Var_Name(1).line,1,3,kk,Num_Basis);
EVAL_STR(4 + (kk-1)*obj.TopDim^2).line =...
[obj.Get_CPP_Tensor_Eval_String(CODE.Var_Name(1).line,kk,2,1), ' = ',...
obj.Get_CPP_Tensor_Eval_String(CODE.Var_Name(1).line,kk,1,2), '; // symmetry!'];
EVAL_STR(5 + (kk-1)*obj.TopDim^2).line = Generate_Evaluation_String(obj,CODE.Var_Name(1).line,2,2,kk,Num_Basis);
EVAL_STR(6 + (kk-1)*obj.TopDim^2).line = Generate_Evaluation_String(obj,CODE.Var_Name(1).line,2,3,kk,Num_Basis);
EVAL_STR(7 + (kk-1)*obj.TopDim^2).line =...
[obj.Get_CPP_Tensor_Eval_String(CODE.Var_Name(1).line,kk,3,1), ' = ',...
obj.Get_CPP_Tensor_Eval_String(CODE.Var_Name(1).line,kk,1,3), '; // symmetry!'];
EVAL_STR(8 + (kk-1)*obj.TopDim^2).line =...
[obj.Get_CPP_Tensor_Eval_String(CODE.Var_Name(1).line,kk,3,2), ' = ',...
obj.Get_CPP_Tensor_Eval_String(CODE.Var_Name(1).line,kk,2,3), '; // symmetry!'];
EVAL_STR(9 + (kk-1)*obj.TopDim^2).line = Generate_Evaluation_String(obj,CODE.Var_Name(1).line,3,3,kk,Num_Basis);
else
error('Not implemented!');
end
end
else
% the map is linear, so the Hessian is ZERO!
Map_Hess_Quad_str = obj.Get_Quad_Pt_CPP_Ref_Var_Name(CODE.Var_Name(1).line);
EVAL_STR.line = [Map_Hess_Quad_str, '.Set_To_Zero(); // map is linear, so hessian is ZERO!'];
end
% define the data type
TYPE_str = obj.Get_CPP_Tensor_Data_Type_Name(obj.GeoDim,obj.TopDim,obj.TopDim);
Defn_Hdr = '// hessian of the transformation';
Loop_Hdr = '// compute the hessian of the local map\n // note: indexing is in the C style';
Loop_Comment = '// sum over basis functions';
CONST_VAR = obj.Lin_PHI_TF;
CODE = obj.create_declaration_and_eval_code(CODE.Var_Name,TYPE_str,EVAL_STR,...
Defn_Hdr,Loop_Hdr,Loop_Comment,CONST_VAR);
%
end
function ES = Generate_Evaluation_String(obj,Var_Name,ii,jj,kk,Num_Basis)
Map_PHI_Hess_str = obj.Get_CPP_Tensor_Eval_String(Var_Name,kk,ii,jj);
ES = [Map_PHI_Hess_str, ' = ']; % init
Partial_Deriv_Str = Get_Mixed_Deriv_String(obj,ii,jj);
for bb=1:Num_Basis
Geo_phi_C_str = ['Geo_Basis_Val_', Partial_Deriv_Str, '[qp_i]', '[', num2str(bb-1), ']']; % C-style indexing
coef_C_str = ['Node_Value', '[', num2str(kk-1), ']', '[kc[', num2str(bb-1), ']]']; % C-style indexing
MULT_str = [Geo_phi_C_str, ' * ', coef_C_str];
ES = [ES, MULT_str];
if (bb < Num_Basis)
ES = [ES, ' + '];
end
end
ES = [ES, ';']; % close the C++ code!
end
function Deriv_Str = Get_Mixed_Deriv_String(obj,ii,jj)
Num_Deriv = [0 0 0]; % init
% MATLAB-style indexing
Num_Deriv(ii) = Num_Deriv(ii) + 1;
Num_Deriv(jj) = Num_Deriv(jj) + 1;
Deriv_Str = obj.Get_Partial_Deriv_String(Num_Deriv);
end
|
github
|
eardi/sm-fpca-master
|
Output_CPP_Eval_Extension.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Transformer/@H1_Trans/Output_CPP_Eval_Extension.m
| 1,117 |
utf_8
|
82df6bc9f41b6b64ca1656254d87ac80
|
function CPP_Eval = Output_CPP_Eval_Extension(obj,FIELD_str,Components)
%Output_CPP_Eval_Extension
%
% This outputs a string representing the C++ evaluation code for the given
% variable name.
%
% Components = [basis_comp_1, basis_comp_2, comp_1, comp_2, etc...]
% Copyright (c) 03-25-2012, Shawn W. Walker
% peel off the basis component
Basis_Comp = Components(1:2);
Components = Components(3:end);
if strcmp(FIELD_str,'Val')
CPP_Eval = ['.a'];
elseif strcmp(FIELD_str,'Grad')
Grad_Comp_C_index_STR = Get_Index_String(Components(1));
CPP_Eval = ['.v', Grad_Comp_C_index_STR];
elseif strcmp(FIELD_str,'d_ds')
CPP_Eval = ['.a'];
elseif strcmp(FIELD_str,'Hess')
Comp_1_C_index_STR = Get_Index_String(Components(1));
Comp_2_C_index_STR = Get_Index_String(Components(2));
CPP_Eval = ['.m', Comp_1_C_index_STR, Comp_2_C_index_STR];
elseif strcmp(FIELD_str,'d2_ds2')
CPP_Eval = ['.a'];
else
error('Not valid!');
end
end
function INDEX_str = Get_Index_String(Index)
% use C-style indexing
INDEX_str = ['[', num2str(Index - 1), ']'];
end
|
github
|
eardi/sm-fpca-master
|
Generic_Write_Basis_Eval_Interpolation_to_CPP_Code.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Function/@GenericFiniteElementFunction/Generic_Write_Basis_Eval_Interpolation_to_CPP_Code.m
| 2,930 |
utf_8
|
83957ab5636c3bbbace2b0157658d68e
|
function status = Generic_Write_Basis_Eval_Interpolation_to_CPP_Code(...
obj,fid,Eval_Basis,COMMENT)
%Generic_Write_Basis_Eval_Interpolation_to_CPP_Code
%
% This encapsulates the code generation for writing the evaluations of
% basis functions (symbolically).
%
% The basis functions have already been composed with the correct map and
% differentiated before this routine is called!
% Copyright (c) 10-28-2016, Shawn W. Walker
status = 0;
Num_Basis = length(Eval_Basis);
ENDL = '\n';
COM_PLUS_TAB = [COMMENT, ' '];
% get info for C++ code
CPP_Type_Info = obj.FuncTrans.Get_Reference_Basis_Function_CPP_Type_Info(obj.Opt);
CPP_Eval_Names = fieldnames(CPP_Type_Info); % get needed options
CPP_Name_Hdr = obj.Get_Basis_Eval_Name_CPP_Hdr([]);
for oi = 1:length(CPP_Eval_Names)
Single_Eval_Name = CPP_Eval_Names{oi};
Num_Vars = length(CPP_Type_Info.(Single_Eval_Name));
for jj = 1:Num_Vars
Tensor_Comp_Set = CPP_Type_Info.(Single_Eval_Name)(jj).Comp;
Derivative_Set = CPP_Type_Info.(Single_Eval_Name)(jj).Deriv;
Eval_Expression = CPP_Type_Info.(Single_Eval_Name)(jj).Expr;
Basis_Sym = Process_Symbolic_Basis_Eval(Eval_Basis,Tensor_Comp_Set,Derivative_Set,Eval_Expression);
% % generate optimized C-code from symbolic expression
% TEST_EXPR = sym(zeros(Num_Basis,length(Tensor_Comp_Set)));
% for bi = 1:Num_Basis
% TEST_EXPR(bi,:) = Basis_Sym(bi).Expr.Func;
% end
% ccode(TEST_EXPR,'file','C:\TEMP\test_code.c');
% declare basis function evaluation string format
Basis_Name_str = [CPP_Name_Hdr, '_', CPP_Type_Info.(Single_Eval_Name)(jj).Suffix_str];
Basis_Eval_Func_str = @(bi,quant) [Basis_Name_str, '[', bi, '].Set_Equal_To(', quant, ');'];
% write basis function evaluation data (for all quad points and
% basis functions).
for bi = 1:Num_Basis
Sym_Expr = Basis_Sym(bi).Expr.Func;
% loop through components
Quant_Eval_str = convert_sym_to_ccode_snip(Sym_Expr(1));
for kk = 2:length(Sym_Expr)
Quant_Eval_str = [Quant_Eval_str, ', ', convert_sym_to_ccode_snip(Sym_Expr(kk))];
end
Basis_Eval_str = Basis_Eval_Func_str(num2str(bi-1),Quant_Eval_str);
fprintf(fid, [COM_PLUS_TAB, Basis_Eval_str, ENDL]);
end
fprintf(fid, ['', ENDL]);
end
end
%fprintf(fid, ['', ENDL]);
end
function Sym_Expr_CC_Snip = convert_sym_to_ccode_snip(Sym_Expr)
C_code_str = ccode(Sym_Expr); % convert to C code!
% remove the standard variable that matlab uses for the final output
Sym_Expr_CC_Snip = regexprep(C_code_str, 't0 =', '');
% trim!
Sym_Expr_CC_Snip = regexprep(Sym_Expr_CC_Snip, ';', '');
Sym_Expr_CC_Snip = strtrim(Sym_Expr_CC_Snip);
end
|
github
|
eardi/sm-fpca-master
|
Generic_Write_Basis_Eval_Interpolation_to_CPP_Code_OLD.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Function/@GenericFiniteElementFunction/Generic_Write_Basis_Eval_Interpolation_to_CPP_Code_OLD.m
| 2,654 |
utf_8
|
81d9a4a1db9871971855df405c57b7b9
|
function status = Generic_Write_Basis_Eval_Interpolation_to_CPP_Code(...
obj,VAR_NAME,NUM_BASIS_str,Largest_Derivative_Order,Tensor_Comp,Eval_Basis,fid_Open,COMMENT)
%Generic_Write_Basis_Eval_Interpolation_to_CPP_Code
%
% This encapsulates the code generation for writing the evaluations of
% basis functions (symbolically).
%
% The basis functions have already been composed with the correct map and
% differentiated before this routine is called!
% Copyright (c) 09-14-2016, Shawn W. Walker
status = 0;
ENDL = '\n';
COM_PLUS_TAB = [COMMENT, ' '];
Len_alpha = Eval_Basis(1).Get_Length_Of_Multiindex;
Local_Basis_Deriv = obj.Get_Local_Basis_Multiindex_Deriv(Len_alpha,Largest_Derivative_Order);
% write out the basis function evaluations
for ind = 1:size(Local_Basis_Deriv,1)
% general comment on evaluating basis functions for specific derivatives
Local_Basis_Deriv_spec = Local_Basis_Deriv(ind,:);
Basis_Title_str = ['// Value of basis function, derivatives = [', num2str(Local_Basis_Deriv_spec),...
'], at local coordinates'];
fprintf(fid_Open, [COM_PLUS_TAB, Basis_Title_str, ENDL]);
% write code for defining the basis functions
Basis_Name_str = obj.Get_Basis_Eval_CPP_Name(VAR_NAME,Local_Basis_Deriv_spec);
Basis_Defn_str = ['double ', Basis_Name_str, '[1][', NUM_BASIS_str, '];'];
fprintf(fid_Open, [COM_PLUS_TAB, Basis_Defn_str, ENDL]);
% loop through all of the basis functions
for bb = 1:length(Eval_Basis)
% C variable name
basis_C_index_str = num2str(bb-1);
Basis_Eval_Name_str = [Basis_Name_str, '[0][', basis_C_index_str, ']'];
% get specific derivative of basis function
alpha = Local_Basis_Deriv_spec(1:Len_alpha);
BF_Deriv_Specific = Eval_Basis(bb).Get_Derivative(alpha);
% only look at one component!
Basis_Differentiate_Sym_Expr = BF_Deriv_Specific.Func(Tensor_Comp(1),Tensor_Comp(2));
% generate code snippet
Basis_Eval_str = make_basis_eval_str(Basis_Eval_Name_str, Basis_Differentiate_Sym_Expr);
fprintf(fid_Open, [COM_PLUS_TAB, Basis_Eval_str, ENDL]);
end
status = fprintf(fid_Open, ['', ENDL]);
end
end
function Basis_Eval_str = make_basis_eval_str(Basis_Eval_Name_str, Sym_Expr)
C_code_str = ccode(Sym_Expr); % convert to C code!
% remove the standard variable that matlab uses for the final output
Basis_Eval_str = regexprep(C_code_str, 't0', Basis_Eval_Name_str);
end
|
github
|
eardi/sm-fpca-master
|
Get_Eval_String.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Function/@FiniteElementCoefFunction/Get_Eval_String.m
| 6,463 |
utf_8
|
4328cd226be8a0388f4512b3257c59c5
|
function [obj, Replacement_str] = Get_Eval_String(obj,input_str,var_str,Geo_Dim,Num_Tuple_in_FE_Space)
%Get_Eval_String
%
% This will parse the coefficient function string. It also sets the options
% (.Opt) of the function.
% Copyright (c) 12-15-2017, Shawn W. Walker
% init
Replacement_str = [];
len_var_str = length(var_str);
% BEGIN: some simple checks
% rough validity check
if length(input_str) < (len_var_str+6)
% disp('Input argument string not long enough!');
% var_str
return;
end
% make sure the *beginning of input_str* matches var_str!
if ~strncmp(input_str,var_str,len_var_str)
% disp('The input_str and var_str are completely different!');
% input_str
% var_str
return;
end
% END: some simple checks
% setup matching strings
CONST_ELEM = ReferenceFiniteElement(constant_one(),true);
BF = FiniteElementBasisFunction(CONST_ELEM);
MATCH_STR = BF.Get_String_Match_Struct;
clear BF CONST_ELEM;
% ultimate check
MATCH_STR_cell = struct2cell(MATCH_STR);
input_str_stripped = obj.Strip_String_Suffix(input_str,MATCH_STR_cell);
clear MATCH_STR_cell;
if ~strcmp(input_str_stripped,var_str)
% 'input_str_stripped' should match 'var_str' exactly, else return
% disp('The input_str_stripped and var_str are not exactly the same!');
% input_str_stripped
% var_str
return;
end
% vector and tuple index string stuff
[Basis_Comp, Tuple_Comp] = obj.Parse_Vector_Tensor_Components(input_str,var_str,Num_Tuple_in_FE_Space);
% convert to linear index k = i + (j-1)*m, where m (n) is the number of rows (cols) in the tuple size,
% and 1 <= i <= m, 1 <= j <= n
Tuple_Comp_Linear_Index = Tuple_Comp(1) + (Tuple_Comp(2)-1) * Num_Tuple_in_FE_Space(1);
Tuple_Comp_c_ind_STR = ['[', num2str(Tuple_Comp_Linear_Index - 1), ']'];
coef_func_STR = [obj.CPP_Var, '->'];
% check if it is the hessian of the function
if ~isempty(regexp(input_str,[var_str, MATCH_STR.hess], 'once'))
str_match_cell = regexp(input_str,[var_str, MATCH_STR.hess], 'match');
str_match = str_match_cell{1};
obj.Opt.Hess = true;
% parse the hessian components
Hess_Comp_1_str = str_match(end-1);
Hess_Comp_2_str = str_match(end);
Hess_Comp = [str2double(Hess_Comp_1_str), str2double(Hess_Comp_2_str)];
if ( max(Hess_Comp) > Geo_Dim )
error('Cannot use derivatives beyond the geometric dimension.');
end
Comp = [Basis_Comp, Hess_Comp];
Replacement_str = Func_Coef_Replacement('Hess',obj.FuncTrans,Comp,coef_func_STR,Tuple_Comp_c_ind_STR);
% check if it is the gradient of the function
elseif ~isempty(regexp(input_str,[var_str, MATCH_STR.grad], 'once'))
str_match_cell = regexp(input_str,[var_str, MATCH_STR.grad], 'match');
str_match = str_match_cell{1};
obj.Opt.Grad = true;
% parse the gradient component
Grad_Comp_str = str_match(end);
Grad_Comp = str2double(Grad_Comp_str);
if Grad_Comp > Geo_Dim
error('Cannot use derivatives beyond the geometric dimension.');
end
Comp = [Basis_Comp, Grad_Comp];
Replacement_str = Func_Coef_Replacement('Grad',obj.FuncTrans,Comp,coef_func_STR,Tuple_Comp_c_ind_STR);
% check if it is the divergence operator
elseif ~isempty(regexp(input_str,[var_str, MATCH_STR.div], 'once'))
obj.Opt.Div = true;
if (obj.Elem.Basis_Size(1) < 2)
error('Can only use "div" operator on functions that are intrinsically vector-valued.');
end
Replacement_str = Func_Coef_Replacement('Div',obj.FuncTrans,Basis_Comp,coef_func_STR,Tuple_Comp_c_ind_STR);
% check if it is the vector curl operator
elseif ~isempty(regexp(input_str,[var_str, MATCH_STR.vector_curl], 'once'))
obj.Opt.Curl = true;
if (obj.Elem.Basis_Size(1) < 2)
error('Can only use "curl" operator on functions that are intrinsically vector-valued.');
end
Replacement_str = Func_Coef_Replacement('Curl',obj.FuncTrans,Basis_Comp,coef_func_STR,Tuple_Comp_c_ind_STR);
% check if it is the scalar curl operator
elseif ~isempty(regexp(input_str,[var_str, MATCH_STR.scalar_curl], 'once'))
obj.Opt.Curl = true;
if (obj.Elem.Basis_Size(1) < 2)
error('Can only use "curl" operator on functions that are intrinsically vector-valued.');
end
Replacement_str = Func_Coef_Replacement('Curl',obj.FuncTrans,Basis_Comp,coef_func_STR,Tuple_Comp_c_ind_STR);
% check if it is the 2nd arc-length derivative along a curve
elseif ~isempty(regexp(input_str,[var_str, MATCH_STR.dsds], 'once'))
obj.Opt.d2_ds2 = true;
if obj.Elem.Top_Dim > 1
error('Cannot use 2nd arc-length derivative in topological dimensions greater than 1.');
end
Replacement_str = Func_Coef_Replacement('d2_ds2',obj.FuncTrans,Basis_Comp,coef_func_STR,Tuple_Comp_c_ind_STR);
% check if it is the 1st arc-length derivative along a curve
elseif ~isempty(regexp(input_str,[var_str, MATCH_STR.ds], 'once'))
obj.Opt.d_ds = true;
if obj.Elem.Top_Dim > 1
error('Cannot use 1st arc-length derivative in topological dimensions greater than 1.');
end
Replacement_str = Func_Coef_Replacement('d_ds',obj.FuncTrans,Basis_Comp,coef_func_STR,Tuple_Comp_c_ind_STR);
% check if it is the value of the function
elseif ~isempty(regexp(input_str,[var_str, MATCH_STR.val], 'once'))
obj.Opt.Val = true;
Replacement_str = Func_Coef_Replacement('Val',obj.FuncTrans,Basis_Comp,coef_func_STR,Tuple_Comp_c_ind_STR);
else
disp('There was no match for the coefficient function:');
input_str
end
if ~isempty(Replacement_str)
if or(isa(obj.FuncTrans,'Hdiv_Trans'),isa(obj.FuncTrans,'Hcurl_Trans'))
% for H(div) and H(curl), we always need the orientation (of the "facets")
obj.Opt.Orientation = true;
end
end
end
function STR = Func_Coef_Replacement(FIELD_STR,FuncTrans,Comp,coef_func_STR,Tuple_Comp_STR)
CPP_Name = FuncTrans.Output_CPP_Var_Name(FIELD_STR);
CPP_Name_w_CF = [coef_func_STR, CPP_Name];
if isa(FuncTrans,'Constant_Trans') % special case for global CONSTANT coefficient functions
STR_begin = [CPP_Name_w_CF, Tuple_Comp_STR];
else
STR_begin = [CPP_Name_w_CF, Tuple_Comp_STR, '[qp]'];
end
Eval_Ext = FuncTrans.Output_CPP_Eval_Extension(FIELD_STR,Comp);
STR = [STR_begin, Eval_Ext];
end
|
github
|
eardi/sm-fpca-master
|
Get_Eval_String.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Function/@FiniteElementBasisFunction/Get_Eval_String.m
| 7,881 |
utf_8
|
0b488bbbcb0dbf9794392c577e07603a
|
function [obj, Replacement_str] = Get_Eval_String(obj,input_str,var_str,Geo_Dim,Num_Tuple_in_FE_Space)
%Get_Eval_String
%
% This will parse the basis function string. It also sets the options
% (.Opt) of the function.
% Copyright (c) 12-15-2017, Shawn W. Walker
% init
Replacement_str = [];
len_var_str = length(var_str);
CONST = strcmp(obj.Type,'CONST'); % is the basis function the constant 1
if ~CONST
%%%%
if length(input_str) < (len_var_str+6)
% disp('Input argument string not long enough!');
% var_str
return;
end
% make sure the *beginning of input_str* matches var_str!
if ~strncmp(input_str,var_str,len_var_str)
% if the variable name does not match what is in the input string,
% then just exit (this isn't the right function anyway!)
return;
end
% setup matching strings
MATCH_STR = obj.Get_String_Match_Struct;
% ultimate check
MATCH_STR_cell = struct2cell(MATCH_STR);
input_str_stripped = obj.Strip_String_Suffix(input_str,MATCH_STR_cell);
clear MATCH_STR_cell;
if ~strcmp(input_str_stripped,var_str)
% 'input_str_stripped' should match 'var_str' exactly, else return
% disp('The input_str_stripped and var_str are not exactly the same!');
% input_str_stripped
% var_str
return;
end
[Basis_Comp, ~] = obj.Parse_Vector_Tensor_Components(input_str,var_str,Num_Tuple_in_FE_Space);
basis_func_STR = [obj.CPP_Var, '->'];
if strcmp(obj.Type,'Test')
basis_index_STR = '[i]'; % row index
elseif strcmp(obj.Type,'Trial')
basis_index_STR = '[j]'; % col index
else
error('Something is wrong!');
end
% check if it is the hessian of the function
if ~isempty(regexp(input_str,[var_str, MATCH_STR.hess], 'once'))
str_match_cell = regexp(input_str,[var_str, MATCH_STR.hess], 'match');
str_match = str_match_cell{1};
obj.Opt.Hess = true;
% parse the hessian components
Hess_Comp_1_str = str_match(end-1);
Hess_Comp_2_str = str_match(end);
Hess_Comp = [str2double(Hess_Comp_1_str), str2double(Hess_Comp_2_str)];
if ( max(Hess_Comp) > Geo_Dim )
error('Cannot use derivatives beyond the geometric dimension.');
end
Replacement_str = Func_Basis_Replacement('Hess',obj.FuncTrans,[Basis_Comp, Hess_Comp],...
basis_func_STR,basis_index_STR);
% check if it is the gradient of the function
elseif ~isempty(regexp(input_str,[var_str, MATCH_STR.grad], 'once'))
str_match_cell = regexp(input_str,[var_str, MATCH_STR.grad], 'match');
str_match = str_match_cell{1};
obj.Opt.Grad = true;
% parse the gradient component
Grad_Comp_str = str_match(end);
Grad_Comp = str2double(Grad_Comp_str);
if Grad_Comp > Geo_Dim
error('Cannot use derivatives beyond the geometric dimension.');
end
Replacement_str = Func_Basis_Replacement('Grad',obj.FuncTrans,[Basis_Comp, Grad_Comp],...
basis_func_STR,basis_index_STR);
% check if it is the divergence operator
elseif ~isempty(regexp(input_str,[var_str, MATCH_STR.div], 'once'))
obj.Opt.Div = true;
if (obj.Elem.Basis_Size(1) < 2)
error('Can only use "div" operator on functions that are intrinsically vector-valued.');
end
Replacement_str = Func_Basis_Replacement('Div',obj.FuncTrans,Basis_Comp,...
basis_func_STR,basis_index_STR);
% check if it is the vector curl operator
elseif ~isempty(regexp(input_str,[var_str, MATCH_STR.vector_curl], 'once'))
obj.Opt.Curl = true;
if (obj.Elem.Basis_Size(1) < 2)
error('Can only use "curl" operator on functions that are intrinsically vector-valued.');
end
Replacement_str = Func_Basis_Replacement('Curl',obj.FuncTrans,Basis_Comp,...
basis_func_STR,basis_index_STR);
% check if it is the scalar curl operator
elseif ~isempty(regexp(input_str,[var_str, MATCH_STR.scalar_curl], 'once'))
obj.Opt.Curl = true;
if (obj.Elem.Basis_Size(1) < 2)
error('Can only use "curl" operator on functions that are intrinsically vector-valued.');
end
Replacement_str = Func_Basis_Replacement('Curl',obj.FuncTrans,Basis_Comp,...
basis_func_STR,basis_index_STR);
% check if it is the 2nd arc-length derivative along a curve
elseif ~isempty(regexp(input_str,[var_str, MATCH_STR.dsds], 'once'))
obj.Opt.d2_ds2 = true;
if obj.Elem.Top_Dim > 1
error('Cannot use 2nd arc-length derivative in topological dimensions greater than 1.');
end
Replacement_str = Func_Basis_Replacement('d2_ds2',obj.FuncTrans,Basis_Comp,...
basis_func_STR,basis_index_STR);
% check if it is the 1st arc-length derivative along a curve
elseif ~isempty(regexp(input_str,[var_str, MATCH_STR.ds], 'once'))
obj.Opt.d_ds = true;
if obj.Elem.Top_Dim > 1
error('Cannot use 1st arc-length derivative in topological dimensions greater than 1.');
end
Replacement_str = Func_Basis_Replacement('d_ds',obj.FuncTrans,Basis_Comp,...
basis_func_STR,basis_index_STR);
% check if it is the value of the function
elseif ~isempty(regexp(input_str,[var_str, MATCH_STR.val], 'once'))
obj.Opt.Val = true;
Replacement_str = Func_Val_Replacement(obj.FuncTrans,Basis_Comp,basis_func_STR,basis_index_STR);
else
% there was no match against a *basis* function;
% but outside this routine, there may be a match to something else,
% like a *coefficient* function or a geometric function.
% so, no need to worry just yet.
% if nothing identifies it, then an error message outside this will
% catch it.
%disp('There was no match for the basis function!');
%input_str
end
end
if ~isempty(Replacement_str)
if or(isa(obj.FuncTrans,'Hdiv_Trans'),isa(obj.FuncTrans,'Hcurl_Trans'))
% for H(div) and H(curl), we always need the orientation (of the "facets")
obj.Opt.Orientation = true;
end
end
end
function STR = Func_Basis_Replacement(FIELD_STR,FuncTrans,Components,basis_func_STR,basis_index_STR)
CPP_Name = FuncTrans.Output_CPP_Var_Name(FIELD_STR);
CPP_Name_w_BF = [basis_func_STR, CPP_Name];
STR_begin = [CPP_Name_w_BF, basis_index_STR, '[qp]'];
Eval_Ext = FuncTrans.Output_CPP_Eval_Extension(FIELD_STR,Components);
STR = [STR_begin, Eval_Ext];
end
function STR = Func_Val_Replacement(FuncTrans,Basis_Comp,basis_func_STR,basis_index_STR)
CPP_Name = FuncTrans.Output_CPP_Var_Name('Val');
if isa(FuncTrans,'H1_Trans') % special case for H^1 functions
% note: we must de-reference here!!!!
CPP_Name_w_BF = ['(*', basis_func_STR, CPP_Name, ')'];
else
CPP_Name_w_BF = [basis_func_STR, CPP_Name];
end
if isa(FuncTrans,'Constant_Trans') % special case for global CONSTANT functions
STR_begin = CPP_Name_w_BF;
else
STR_begin = [CPP_Name_w_BF, basis_index_STR, '[qp]'];
end
Eval_Ext = FuncTrans.Output_CPP_Eval_Extension('Val',Basis_Comp);
STR = [STR_begin, Eval_Ext];
end
|
github
|
eardi/sm-fpca-master
|
Write_Basis_Func_Eval_3D_Hcurl_snip.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Function/@FiniteElementBasisFunction/private/Write_Basis_Func_Eval_3D_Hcurl_snip.m
| 2,198 |
utf_8
|
37a1c290a98f63935c0ba1ebb1d60cf6
|
function status = Write_Basis_Func_Eval_3D_Hcurl_snip(obj,fid,Largest_Derivative_Order,Map_Basis,Quad)
%Write_Basis_Func_Eval_3D_Hcurl_snip
%
% This does part of the job of "Write_Basis_Func_Eval_snip" except for
% H(curl) elements in 3-D (because they are a PITA).
% Copyright (c) 11-08-2016, Shawn W. Walker
% load mirror image basis set
FuncName = [obj.Elem.Element_Name, '_mirror_image();'];
Mirror_Elem = eval(FuncName);
% put into a better object
Mirror_RefElem = ReferenceFiniteElement(Mirror_Elem);
% get basis functions on reference element
Quad_NOT_USED = obj.Elem.Gen_Quadrature_Rule(1, obj.Elem.Simplex_Type); % bogus! not really used
Eval_Basis = obj.Elem.Gen_Basis_Function_Evals(Quad_NOT_USED.Pt,Largest_Derivative_Order);
Eval_Basis_Mirror = Mirror_RefElem.Gen_Basis_Function_Evals(Quad_NOT_USED.Pt,Largest_Derivative_Order);
ENDL = '\n';
TAB = ' ';
TAB2 = [TAB, TAB];
TAB3 = [TAB, TAB, TAB];
% begin massive switch statement
fprintf(fid, [TAB, '// choose basis evaluations based on element order', ENDL]);
fprintf(fid, [TAB, 'if (Std_Elem_Order) // V_1 < V_2 < V_3 < V_4', ENDL]);
fprintf(fid, [TAB2, '{', ENDL]);
disp(['##write basis evals for ascending order.']);
status = write_basis_set(obj,fid,Eval_Basis,Map_Basis,Quad,TAB);
fprintf(fid, [TAB2, '}', ENDL]);
fprintf(fid, [TAB, 'else // V_1 < V_3 < V_2 < V_4', ENDL]);
fprintf(fid, [TAB2, '{', ENDL]);
disp(['##write basis evals for mirror image ascending order.']);
status = write_basis_set(obj,fid,Eval_Basis_Mirror,Map_Basis,Quad,TAB);
fprintf(fid, [TAB2, '}', ENDL]);
fprintf(fid, [TAB, '// END: choose basis evaluations based on element order', ENDL]);
end
function status = write_basis_set(obj,fid,Eval_Basis,Map_Basis,Quad,TAB)
% map all basis functions
for bb = 1:length(Eval_Basis)
% compose basis functions (and their derivatives) with Codim Map,
% i.e. we are plugging in the map after differentiating.
Eval_Basis(bb) = Eval_Basis(bb).Compose_With_Function(Map_Basis.Codim_Map);
end
% write out the finite element function basis evaluations
status = obj.Generic_Write_Basis_Eval_to_CPP_Code(Quad.Pt,fid,Eval_Basis,TAB);
end
|
github
|
eardi/sm-fpca-master
|
Write_Basis_Eval_Interpolation_3D_Hcurl_snip.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Function/@FiniteElementBasisFunction/private/Write_Basis_Eval_Interpolation_3D_Hcurl_snip.m
| 2,241 |
utf_8
|
e29dad7a1ce1538238dac756ebd49585
|
function status = Write_Basis_Eval_Interpolation_3D_Hcurl_snip(obj,fid,Largest_Derivative_Order,Map_Basis)
%Write_Basis_Eval_Interpolation_3D_Hcurl_snip
%
% This does part of the job of "Write_Basis_Eval_Interpolation_snip"
% except for H(curl) elements in 3-D (because they are a PITA).
% Copyright (c) 11-13-2016, Shawn W. Walker
% load mirror image basis set
FuncName = [obj.Elem.Element_Name, '_mirror_image();'];
Mirror_Elem = eval(FuncName);
% put into a better object
Mirror_RefElem = ReferenceFiniteElement(Mirror_Elem);
% get basis functions on reference element
Quad_NOT_USED = obj.Elem.Gen_Quadrature_Rule(1, obj.Elem.Simplex_Type); % bogus! not really used
Eval_Basis = obj.Elem.Gen_Basis_Function_Evals(Quad_NOT_USED.Pt,Largest_Derivative_Order);
Eval_Basis_Mirror = Mirror_RefElem.Gen_Basis_Function_Evals(Quad_NOT_USED.Pt,Largest_Derivative_Order);
ENDL = '\n';
TAB = ' ';
TAB2 = [TAB, TAB];
TAB3 = [TAB, TAB, TAB];
% begin massive switch statement
fprintf(fid, [TAB, '// choose basis evaluations based on element order', ENDL]);
fprintf(fid, [TAB, 'if (Std_Elem_Order) // V_1 < V_2 < V_3 < V_4', ENDL]);
fprintf(fid, [TAB2, '{', ENDL]);
disp(['##write basis interpolation for ascending order.']);
status = write_basis_set(obj,fid,Eval_Basis,Map_Basis,TAB);
fprintf(fid, [TAB2, '}', ENDL]);
fprintf(fid, [TAB, 'else // V_1 < V_3 < V_2 < V_4', ENDL]);
fprintf(fid, [TAB2, '{', ENDL]);
disp(['##write basis interpolation for mirror image ascending order.']);
status = write_basis_set(obj,fid,Eval_Basis_Mirror,Map_Basis,TAB);
fprintf(fid, [TAB2, '}', ENDL]);
fprintf(fid, [TAB, '// END: choose basis evaluations based on element order', ENDL]);
end
function status = write_basis_set(obj,fid,Eval_Basis,Map_Basis,TAB)
% map all basis functions
for bb = 1:length(Eval_Basis)
% compose basis functions (and their derivatives) with Codim Map,
% i.e. we are plugging in the map after differentiating.
Eval_Basis(bb) = Eval_Basis(bb).Compose_With_Function(Map_Basis.Codim_Map);
end
% write out the FE basis function evaluations (at interpolation points)
status = obj.Generic_Write_Basis_Eval_Interpolation_to_CPP_Code(fid,Eval_Basis,TAB);
end
|
github
|
eardi/sm-fpca-master
|
Gen_Basis_Function_Class_Defn.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Function/@FiniteElementBasisFunction/private/Gen_Basis_Function_Class_Defn.m
| 4,336 |
utf_8
|
aacaf3a8d0cfa90215ebe9c4d58ff7bd
|
function [status, Premap_CODE] = Gen_Basis_Function_Class_Defn(obj,fid,BF_CODE)
%Gen_Basis_Function_Class_Defn
%
% This declares the Basis_Function_Class definition.
% Copyright (c) 01-15-2018, Shawn W. Walker
ENDL = '\n';
TAB = ' ';
TAB2 = [TAB, TAB];
%%%%%%%
% output text-lines
fprintf(fid, ['', ENDL]);
fprintf(fid, ['/* C++ (Specific) FE Function class definition */', ENDL]);
fprintf(fid, ['class SpecificFUNC: public ABSTRACT_FEM_Function_Class // derive from base class', ENDL]);
fprintf(fid, ['{', ENDL]);
fprintf(fid, ['public:', ENDL]);
fprintf(fid, [TAB, 'int* Elem_DoF[NB]; // element DoF list', ENDL]);
fprintf(fid, ['', ENDL]);
fprintf(fid, [TAB, '// data structure containing information on the function evaluations.', ENDL]);
fprintf(fid, [TAB, '// Note: this data is evaluated at several quadrature points!', ENDL]);
% write the basis function variable declarations
[VAL_CODE, CONST_VAL_CODE] = special_case(obj);
if ~isempty(VAL_CODE)
DECLARE = VAL_CODE.Defn;
for di=1:length(DECLARE)
fprintf(fid, [TAB, DECLARE(di).line, ENDL]);
end
end
if ~isempty(CONST_VAL_CODE)
DECLARE = CONST_VAL_CODE.Defn;
for di=1:length(DECLARE)
fprintf(fid, [TAB, DECLARE(di).line, ENDL]);
end
end
for ind=1:length(BF_CODE)
DECLARE = BF_CODE(ind).Defn;
for di=1:length(DECLARE)
fprintf(fid, [TAB, DECLARE(di).line, ENDL]);
end
end
fprintf(fid, ['', ENDL]);
fprintf(fid, [TAB, '// constructor', ENDL]);
fprintf(fid, [TAB, 'SpecificFUNC ();', ENDL]);
fprintf(fid, [TAB, '~SpecificFUNC (); // destructor', ENDL]);
fprintf(fid, [TAB, 'void Setup_Function_Space(const mxArray*);', ENDL]);
fprintf(fid, [TAB, 'void Get_Local_to_Global_DoFmap(const int&, int*) const;', ENDL]);
fprintf(fid, [TAB, ' // need the "const" to ENSURE that nothing in this object will change!', ENDL]);
fprintf(fid, [TAB, 'void Transform_Basis_Functions();', ENDL]);
fprintf(fid, [TAB, 'const ', obj.GeomFunc.CPP.Data_Type_Name, '* Mesh;', ENDL]);
fprintf(fid, ['', ENDL]);
fprintf(fid, ['private:', ENDL]);
% for H(div) and H(curl), we need a special pre-map function
if or(isa(obj.FuncTrans,'Hdiv_Trans'),isa(obj.FuncTrans,'Hcurl_Trans'))
Premap_CODE = obj.FuncTrans.Get_Premap_Transformation(obj.Elem);
fprintf(fid, [TAB, 'void ', Premap_CODE.CPP_Name, '(', Premap_CODE.Arg_List_Init,') const;', ENDL]);
% elseif isa(obj.FuncTrans,'Hcurl_Trans')
% Premap_CODE = obj.FuncTrans.Get_Premap_Transformation(obj.Elem);
% fprintf(fid, [TAB, 'void ', Premap_CODE.CPP_Name, '(', Premap_CODE.Arg_List_Init,') const;', ENDL]);
else
Premap_CODE = [];
end
CDMap = Codim_Map(obj.GeomFunc);
Compute_Local_Transformation = CDMap.Get_Basis_Function_Local_Transformation;
% only do this if the basis functions are NOT global constants!
if isempty(CONST_VAL_CODE)
for ind = 1:Compute_Local_Transformation.Num_Map_Basis
% Map_Basis...
fprintf(fid, [TAB, 'void ', Compute_Local_Transformation.Map_Basis(ind).CPP_Name, '();', ENDL]);
end
end
if ~isempty(VAL_CODE) % special case code for H^1 function evaluation
for ind = 1:Compute_Local_Transformation.Num_Map_Basis
fprintf(fid, [TAB, Compute_Local_Transformation.Map_Basis(ind).Val.Declare_CPP, ENDL]);
end
for ind = 1:Compute_Local_Transformation.Num_Map_Basis
fprintf(fid, [TAB, 'void ', Compute_Local_Transformation.Map_Basis(ind).Val.CPP_Routine,...
'(SCALAR V[NB][NQ]);', ENDL]);
end
end
status = fprintf(fid, ['};', ENDL]);
status = fprintf(fid, ['', ENDL]);
end
function [VAL_CODE, CONST_VAL_CODE] = special_case(obj)
% SPECIAL CASE
% only do this for H^1 functions (and only if we are not generating
% interpolation code)
if and(isa(obj.FuncTrans,'H1_Trans'),~obj.INTERPOLATION)
% we will compute this ONCE for all elements
VAL_CODE = obj.FuncTrans(1).FUNC_Val_C_Code; % we can just take the first one
else
VAL_CODE = [];
end
% SPECIAL CASE
% only do this for global constant basis functions
if isa(obj.FuncTrans,'Constant_Trans')
% we will compute this ONCE and for all
CONST_VAL_CODE = obj.FuncTrans(1).FUNC_Val_C_Code; % we can just take the first one
else
CONST_VAL_CODE = [];
end
end
|
github
|
eardi/sm-fpca-master
|
Get_Eval_String.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Function/@GeometricElementFunction/Get_Eval_String.m
| 9,080 |
utf_8
|
bb4eaf4c05d80983f9c24b6b62f1f2e0
|
function [obj, Replacement_str] = Get_Eval_String(obj,input_str,domain_choice)
%Get_Eval_String
%
% This will parse the geom function string. domain_choice selects either the Subdomain
% geometry or the Domain of Integration (DoI) geometry.
% Copyright (c) 01-24-2014, Shawn W. Walker
% SWW: could there be a mistake if the end of input_str matches domain_choice?
MATCH_STR = obj.Get_String_Match_Struct;
% concatenate 'geom' and domain name string
if strcmp(domain_choice,'DoI')
% we want the Domain of Integration (DoI)
geom_domain_str = [obj.Func_Name, obj.Domain.Integration_Domain.Name];
else
% assume we want the subdomain
geom_domain_str = [obj.Func_Name, obj.Domain.Subdomain.Name];
end
% init
Replacement_str = [];
%Comp = 1;
len_geom_domain_str = length(geom_domain_str);
% get geometric dimension
GeoDim = obj.Domain.Integration_Domain.GeoDim;
% make sure we only make replacement when the given variable name is on the
% same domain
if ~strncmp(input_str,geom_domain_str,len_geom_domain_str)
% if the domains are different, just exit!
return;
end
mesh_func_STR = [obj.CPP.Identifier_Name, '->'];
% check if it is the mesh size
if ~isempty(regexp(input_str,[geom_domain_str, MATCH_STR.mesh_size], 'once'))
obj.Opt.Mesh_Size = true;
% setup the C-code evaluation string
CPP_Name = obj.GeoTrans.Output_CPP_Var_Name('Mesh_Size');
CPP_Name_w_Mesh = [mesh_func_STR, CPP_Name];
Replacement_str = [CPP_Name_w_Mesh, '[0]', '.a'];
% check if it is the derivative of the coordinate function
elseif ~isempty(regexp(input_str,[geom_domain_str, MATCH_STR.coord_deriv], 'once'))
% parse X, Y, or Z component
X_Comp_str = input_str(len_geom_domain_str+3);
% get coord component
X_Comp = str2double(X_Comp_str);
% parse derivative component
Deriv_Comp_str = input_str(len_geom_domain_str+10);
% get s_1, s_2 derivative component
Deriv_Comp = str2double(Deriv_Comp_str);
if (X_Comp > GeoDim)
error('Coordinate component cannot be larger than geometric dimension.');
end
if (Deriv_Comp > obj.Elem.Top_Dim)
error('Derivative component cannot be larger than topological dimension.');
end
obj.Opt.Grad = true;
% setup the C-code evaluation string
C_style_X_Comp = X_Comp-1;
C_style_Deriv_Comp = Deriv_Comp-1;
CPP_Name = obj.GeoTrans.Output_CPP_Var_Name('Grad');
CPP_Name_w_Mesh = [mesh_func_STR, CPP_Name];
QP_str = get_quad_pt_str(obj,'Grad');
Replacement_str = [CPP_Name_w_Mesh, QP_str, '.m[', num2str(C_style_X_Comp), '][', num2str(C_style_Deriv_Comp), ']'];
% check if it is the PHYSICAL GRADIENT (e.g. like the surface gradient) of the coordinate function
% this is just the tangent space projection!
elseif ~isempty(regexp(input_str,[geom_domain_str, MATCH_STR.tan_space_proj], 'once'))
% parse X, Y, or Z component
X_Comp_str = input_str(len_geom_domain_str+6);
% get coord component
X_Comp = str2double(X_Comp_str);
% parse grad component
Grad_Comp_str = input_str(len_geom_domain_str+7);
% get grad component
Grad_Comp = str2double(Grad_Comp_str);
if (X_Comp > GeoDim)
error('Coordinate component cannot be larger than geometric dimension.');
end
if (Grad_Comp > GeoDim)
error('Physical gradient component cannot be larger than geometric dimension.');
end
obj.Opt.Tangent_Space_Projection = true;
% setup the C-code evaluation string
C_style_X_Comp = X_Comp-1;
C_style_Grad_Comp = Grad_Comp-1;
CPP_Name = obj.GeoTrans.Output_CPP_Var_Name('Tangent_Space_Projection');
CPP_Name_w_Mesh = [mesh_func_STR, CPP_Name];
QP_str = get_quad_pt_str(obj,'Tangent_Space_Projection');
Replacement_str = [CPP_Name_w_Mesh, QP_str, '.m[', num2str(C_style_X_Comp), '][', num2str(C_style_Grad_Comp), ']'];
% check if it is the coordinate function
elseif ~isempty(regexp(input_str,[geom_domain_str, MATCH_STR.coord_val], 'once'))
% parse X, Y, or Z component
X_Comp_str = input_str(len_geom_domain_str+3);
% get coord component
X_Comp = str2double(X_Comp_str);
if (X_Comp > GeoDim)
error('Coordinate component cannot be larger than geometric dimension.');
end
obj.Opt.Val = true;
% setup the C-code evaluation string
C_style_X_Comp = X_Comp-1;
CPP_Name = obj.GeoTrans.Output_CPP_Var_Name('Val');
CPP_Name_w_Mesh = [mesh_func_STR, CPP_Name];
QP_str = get_quad_pt_str(obj,'Val');
Replacement_str = [CPP_Name_w_Mesh, QP_str, '.v[', num2str(C_style_X_Comp), ']'];
% check if it is the tangent vector
elseif ~isempty(regexp(input_str,[geom_domain_str, MATCH_STR.tangent], 'once'))
% parse component
Comp_str = input_str(len_geom_domain_str+3);
% set component
Comp = str2double(Comp_str);
obj.Opt.Tangent_Vector = true;
% setup the C-code evaluation string
C_style_Comp = Comp-1;
CPP_Name = obj.GeoTrans.Output_CPP_Var_Name('Tangent_Vector');
CPP_Name_w_Mesh = [mesh_func_STR, CPP_Name];
QP_str = get_quad_pt_str(obj,'Tangent_Vector');
Replacement_str = [CPP_Name_w_Mesh, QP_str, '.v[', num2str(C_style_Comp), ']'];
% check if it is the normal vector
elseif ~isempty(regexp(input_str,[geom_domain_str, MATCH_STR.normal], 'once'))
% parse component
Comp_str = input_str(len_geom_domain_str+3);
% set component
Comp = str2double(Comp_str);
obj.Opt.Normal_Vector = true;
% setup the C-code evaluation string
C_style_Comp = Comp-1;
CPP_Name = obj.GeoTrans.Output_CPP_Var_Name('Normal_Vector');
CPP_Name_w_Mesh = [mesh_func_STR, CPP_Name];
QP_str = get_quad_pt_str(obj,'Normal_Vector');
Replacement_str = [CPP_Name_w_Mesh, QP_str, '.v[', num2str(C_style_Comp), ']'];
% check if it is the curvature vector
elseif ~isempty(regexp(input_str,[geom_domain_str, MATCH_STR.curvvec], 'once'))
% parse component
Comp_str = input_str(len_geom_domain_str+10);
% set component
Comp = str2double(Comp_str);
obj.Opt.Total_Curvature_Vector = true;
% setup the C-code evaluation string
C_style_Comp = Comp-1;
CPP_Name = obj.GeoTrans.Output_CPP_Var_Name('Total_Curvature_Vector');
CPP_Name_w_Mesh = [mesh_func_STR, CPP_Name];
QP_str = get_quad_pt_str(obj,'Total_Curvature_Vector');
Replacement_str = [CPP_Name_w_Mesh, QP_str, '.v[', num2str(C_style_Comp), ']'];
% check if it is the (total) scalar curvature
elseif ~isempty(regexp(input_str,[geom_domain_str, MATCH_STR.curv], 'once'))
obj.Opt.Total_Curvature = true;
% setup the C-code evaluation string
CPP_Name = obj.GeoTrans.Output_CPP_Var_Name('Total_Curvature');
CPP_Name_w_Mesh = [mesh_func_STR, CPP_Name];
QP_str = get_quad_pt_str(obj,'Total_Curvature');
Replacement_str = [CPP_Name_w_Mesh, QP_str, '.a'];
% check if it is the gauss curvature
elseif ~isempty(regexp(input_str,[geom_domain_str, MATCH_STR.gauss_curv], 'once'))
obj.Opt.Gauss_Curvature = true;
% setup the C-code evaluation string
CPP_Name = obj.GeoTrans.Output_CPP_Var_Name('Gauss_Curvature');
CPP_Name_w_Mesh = [mesh_func_STR, CPP_Name];
QP_str = get_quad_pt_str(obj,'Gauss_Curvature');
Replacement_str = [CPP_Name_w_Mesh, QP_str, '.a'];
% check if it is the shape operator
elseif ~isempty(regexp(input_str,[geom_domain_str, MATCH_STR.shape_op], 'once'))
% parse the components of the shape operator
Comp_1_str = input_str(len_geom_domain_str+11);
Comp_2_str = input_str(len_geom_domain_str+12);
% get component indices
Comp_1 = str2double(Comp_1_str);
Comp_2 = str2double(Comp_2_str);
if or(Comp_1 > GeoDim, Comp_2 > GeoDim)
error('Component indices (for the shape operator) cannot be larger than the geometric dimension.');
end
obj.Opt.Shape_Operator = true;
% setup the C-code evaluation string
C_style_Comp_1 = Comp_1 - 1;
C_style_Comp_2 = Comp_2 - 1;
CPP_Name = obj.GeoTrans.Output_CPP_Var_Name('Shape_Operator');
CPP_Name_w_Mesh = [mesh_func_STR, CPP_Name];
QP_str = get_quad_pt_str(obj,'Shape_Operator');
Replacement_str = [CPP_Name_w_Mesh, QP_str, '.m[', num2str(C_style_Comp_1), '][', num2str(C_style_Comp_2), ']'];
else
disp('There was no match for the geometric function:');
input_str
disp(' on this domain:')
geom_domain_str
end
end
function QP_str = get_quad_pt_str(obj,FIELD_str)
CONST_VAR = obj.GeoTrans.Is_Quantity_Constant(FIELD_str);
if CONST_VAR
% there is only one quad point
QP_str = '[0]';
else
% the map is non-linear, so we have several quad points
QP_str = '[qp]';
end
end
|
github
|
eardi/sm-fpca-master
|
Write_SUBRoutine_Compute_Map.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Function/@GeometricElementFunction/private/Write_SUBRoutine_Compute_Map.m
| 3,451 |
utf_8
|
5345521c7f3161f99ade27be2c9724b8
|
function status = Write_SUBRoutine_Compute_Map(obj,fid,Geo_CODE,Compute_Map)
%Write_SUBRoutine_Compute_Map
%
% This generates a sub-routine of the Mesh_Geometry_Class for computing
% transformations of the local element map.
% Copyright (c) 03-10-2012, Shawn W. Walker
ENDL = '\n';
% insert code snippet
fprintf(fid, ['', ENDL]);
fprintf(fid, [obj.BEGIN_Auto_Gen, ENDL]);
fprintf(fid, ['/***************************************************************************************/', ENDL]);
fprintf(fid, ['/* compute the local transformation from the standard reference element', ENDL]);
fprintf(fid, [' to an element in the Mesh */', ENDL]);
fprintf(fid, ['void MGC::', Compute_Map.CPP_Name,...
'(const int& elem_index) // current mesh element index', ENDL]);
fprintf(fid, ['{', ENDL]);
% fprintf(fid, ['int kc[NB]; // for indexing through the mesh DoFmap', ENDL]);
% fprintf(fid, ['', ENDL]);
fprintf(fid, ['Get_Local_to_Global_DoFmap(elem_index, kc);', ENDL]);
fprintf(fid, ['', ENDL]);
% get number of derivatives to compute
Num_Deriv = obj.GeoTrans.Number_Of_Derivatives_For_Opt(obj.Opt);
% insert basis function evaluations at the quad points
if obj.INTERPOLATION
% no quad points here
status = obj.Write_Geometry_Basis_Eval_Interpolation_snip(fid,Num_Deriv,Compute_Map);
else
status = obj.Write_Geometry_Basis_Eval_snip(fid,Num_Deriv,Compute_Map);
end
% insert basis function evaluations at the local vertex coordinates
special_case_for_mesh_size(obj,fid,Compute_Map);
% now insert the geometry computation code
obj.Write_Geometry_Computation_Code_snippets(fid,Geo_CODE);
fprintf(fid, ['}', ENDL]);
fprintf(fid, ['/***************************************************************************************/', ENDL]);
fprintf(fid, [obj.END_Auto_Gen, ENDL]);
end
function status = special_case_for_mesh_size(obj,fid,Compute_Map)
% if you want the mesh size
if (obj.Opt.Mesh_Size)
% then you need some extra basis function evaluations
% get bogus quadrature rule on the ref elem
Quad_NOT_USED = obj.Elem.Gen_Quadrature_Rule(1, obj.Elem.Simplex_Type);
% get basis functions on reference element
Eval_Basis = obj.Elem.Gen_Basis_Function_Evals(Quad_NOT_USED.Pt,0);
% map geometric basis functions onto local mesh entity
CDMap = Codim_Map(obj);
Eval_Basis = CDMap.Map_Geometric_Basis_Function_Evals(Eval_Basis,Compute_Map.Codim_Map);
% get the "corner vertices" of the local topological entity
Quad.Pt = Get_Local_Simplex_Vertex_Coordinates(Compute_Map);
Num_Quad_str = num2str(size(Quad.Pt,1));
for bb = 1:length(Eval_Basis)
% evaluate all of the basis functions at the corner vertices
% (on the local mesh entity)
Eval_Basis(bb) = Eval_Basis(bb).Fill_Eval(Quad.Pt);
end
ENDL = '\n';
% output text-lines
fprintf(fid, [obj.BEGIN_Auto_Gen, ENDL]);
OUTSTR = ['// basis function evaluations at the local element vertices'];
fprintf(fid, [OUTSTR, ENDL]);
Pick_Deriv = [0];
status = obj.Generic_Write_Basis_Eval_to_CPP_Code_OLD('Geo_Vtx',Num_Quad_str,'NB',Eval_Basis,[1 1],Pick_Deriv,fid,'');
% NEXT, quad points
COMMENT = '// ';
status = obj.Gen_Quad_Point_CPP_Code(Quad.Pt,fid,COMMENT,'GLOBAL_TD');
fprintf(fid, [obj.END_Auto_Gen, ENDL]);
end
end
|
github
|
eardi/sm-fpca-master
|
Parse_Integrals.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Level_1/@Real/Parse_Integrals.m
| 3,939 |
utf_8
|
26556a155ae47c4c4a594c765b64c938
|
function [Parsed, Num_Nonzeros] = Parse_Integrals(obj)
%Parse_Integrals
%
% This parses the integrals (in a Real matrix) into a more useable struct.
%
% [Parsed, Num_Nonzeros] = obj.Parse_Integrals;
%
% Parsed = array (length M) of structs:
% .Integrand_Sym(:,:) = RxC sym expression (R,C is the row and col
% dimensions of 'obj').
% .Domain = RxC cell array of Level 1 Domains (corresponding to
% Integrand_Sym).
% .TestF = [].
% .TrialF = [].
% Note: Parsed(k) corresponds to the unique kth Domain of Integration.
% Num_Nonzeros = column vector (length M) where Num_Nonzeros(i) is the number
% of non-zero terms in the matrix: Parsed(i).Integrand_Sym.
% Copyright (c) 06-22-2012, Shawn W. Walker
% example:
%
% suppose this object (obj) is 2x2, with integrals for each entry looking like:
%
% ----------------------------------------------------------------------
% | \int_\Omega ... + \int_\Gamma | \int_\Omega |
% ----------------------------------------------------------------------
% | \int_\Gamma | 0 |
% ----------------------------------------------------------------------
%
% this routine creates an array of structs that mimics this:
%
% Parsed(1).Integrand_Sym(:,:) are integrands evaluated on \int_\Omega:
% ----------------------------------------------------------------------
% | \int_\Omega | \int_\Omega |
% ----------------------------------------------------------------------
% | 0 | 0 |
% ----------------------------------------------------------------------
%
% Parsed(2).Integrand_Sym(:,:) are integrands evaluated on \int_\Gamma:
% ----------------------------------------------------------------------
% | \int_\Gamma | 0 |
% ----------------------------------------------------------------------
% | \int_\Gamma | 0 |
% ----------------------------------------------------------------------
% get unique list of integration domains
Domains = containers.Map;
for ind = 1:length(obj(:))
if ~isempty(obj(ind).Integral)
Domains(obj(ind).Integral.Domain.Name) = obj(ind).Integral.Domain;
end
end
DoI_Names = Domains.keys;
% manually init Parsed structure
Parsed = get_parsed_struct;
for di = 1:length(DoI_Names)
Parsed(di).Integrand_Sym = sym(zeros(size(obj))); % all zero sym matrix
Parsed(di).Domain = cell(size(obj));
for ir = 1:size(obj,1)
for ic = 1:size(obj,2)
% fill with the *same* domain
Parsed(di).Domain{ir,ic} = Domains(DoI_Names{di});
end
end
end
% now fill the integrand
Num_Nonzeros = zeros(length(Parsed),1);
for ri = 1:size(obj,1)
for ci = 1:size(obj,2)
% get the Integral object (array) for the (ri,ci) entry in the "Real" matrix
ID = obj(ri,ci).Integral;
% loop through all of the individual Integral(s)
for ii = 1:length(ID)
% loop through each unique Domain
for pp = 1:length(Parsed)
% if the Integral's Domain matches,
if isequal(ID(ii).Domain,Parsed(pp).Domain{1,1})
% then store it in the Parsed structure according to that Domain
Parsed(pp).Integrand_Sym(ri,ci) = ID.Integrand;
Num_Nonzeros(pp) = Num_Nonzeros(pp) + 1;
end
end
end
end
end
end
function SS = get_parsed_struct()
SS.Integrand_Sym = [];
SS.Domain = [];
SS.TestF = [];
SS.TrialF = [];
end
|
github
|
eardi/sm-fpca-master
|
Add_Integral.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Level_1/@genericform/Add_Integral.m
| 2,585 |
utf_8
|
0caf46b517c35633d5df30b374180613
|
function obj = Add_Integral(obj,Int_Obj)
%Add_Integral
%
% This adds an Integral object to the genericform object.
%
% obj = obj.Add_Integral(Int_Obj);
%
% Int_Obj = a Level 1 Integral object.
% Copyright (c) 05-25-2012, Shawn W. Walker
if or(size(obj,1) > 1,size(obj,2) > 1)
disp('This object is an array!');
error('You must index the object you want!');
end
if ~isa(Int_Obj,'Integral')
error('Input must be an Integral object!');
end
% check that the Test, and/or Trial functions match the Test and Trial spaces.
check_test_trial_space(obj.Test_Space,Int_Obj.TestF,'Test',Int_Obj.Integrand);
check_test_trial_space(obj.Trial_Space,Int_Obj.TrialF,'Trial',Int_Obj.Integrand);
obj.Verify_Multilinearity_Of_Form(Int_Obj);
[obj, SUCCESS] = obj.Try_To_Combine_Integrals(Int_Obj);
if ~SUCCESS
% add in the integral
Num_Int = length(obj.Integral);
if (Num_Int==0)
obj.Integral = Int_Obj;
else
obj.Integral(Num_Int+1) = Int_Obj;
end
end
end
function check_test_trial_space(Space,FUNC,FUNC_str,Integrand)
err = FELerror;
if isempty(Space)
if ~isempty(FUNC)
err = err.Add_Comment(['Form does not have a ', FUNC_str, ' space defined.']);
err = err.Add_Comment(['The problem is with this function: ', FUNC.Name]);
err = err.Add_Comment(['There should be *no* ', FUNC_str, ' function in the Integral''s integrand:']);
err = err.Add_Comment([' ', char(Integrand)]);
err.Error;
error('stop!');
end
else
if isempty(FUNC)
err = err.Add_Comment(['Form has a ', FUNC_str, ' space defined: ', Space.Name]);
err = err.Add_Comment(['There is *no* ', FUNC_str, ' function in the Integral''s integrand:']);
err = err.Add_Comment([' ', char(Integrand)]);
err = err.Add_Comment(' ');
err = err.Add_Comment(['The integrand *must* have a ', FUNC_str, ' function in it!']);
err.Error;
error('stop!');
else
if ~isequal(Space,FUNC.Element)
err = err.Add_Comment(['The form''s ', FUNC_str, ' space does not match the ', FUNC_str, ' function''s space.']);
err = err.Add_Comment(['The problem is either with this function: ', FUNC.Name]);
err = err.Add_Comment([' OR with this space: ', Space.Name]);
err = err.Add_Comment(['Check that you have the correct ', FUNC_str, ' function and/or space!']);
err.Error;
error('stop!');
end
end
end
end
|
github
|
eardi/sm-fpca-master
|
Verify_Multilinearity_Of_Form.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Level_1/@genericform/private/Verify_Multilinearity_Of_Form.m
| 3,504 |
utf_8
|
c6daa4caa5819c4f4e7f9c2050836b23
|
function Verify_Multilinearity_Of_Form(obj,Int_Obj)
%Verify_Multilinearity_Of_Form
%
% This checks the symbolic expression that defines the integrand of Int_Obj, and
% verifies that it has the proper "form", i.e. the expression should define a proper
% bilinear or linear form (as the case may be).
%
% obj.Verify_Multilinearity_Of_Form(Int_Obj);
%
% Int_Obj = a Level 1 Integral object.
% Copyright (c) 08-08-2013, Shawn W. Walker
% store for later
Integrand_String = char(Int_Obj.Integrand);
Vars = symvar(Int_Obj.Integrand);
VALID_TESTF = check_linearity(Int_Obj.Integrand,Vars,Int_Obj.TestF);
VALID_TRIALF = check_linearity(Int_Obj.Integrand,Vars,Int_Obj.TrialF);
% both variables must be linear!
VALID = and(VALID_TESTF,VALID_TRIALF);
BILIN = isa(obj,'Bilinear');
LIN = isa(obj,'Linear');
if (BILIN)
if ~VALID
err = FELerror;
err = err.Add_Comment(['Cannot include the following integrand into the current Bilinear form.']);
err = err.Add_Comment(['Integrand: ', Integrand_String]);
err = err.Add_Comment(' ');
err = err.Add_Comment(['The integrand must have the following format:']);
err = err.Add_Comment(' ');
err = err.Add_Comment([' term #1 + term #2 + term #3 + ...']);
err = err.Add_Comment(' ');
err = err.Add_Comment(['where each "term" includes a *product* of a single Test function with a single Trial function.']);
err = err.Add_Comment(['Otherwise, the integrand is *not* a BILINEAR form!']);
err.Error;
error('stop!');
end
elseif (LIN)
if ~VALID
err = FELerror;
err = err.Add_Comment(['Cannot include the following integrand into the current Linear form.']);
err = err.Add_Comment(['Integrand: ', Integrand_String]);
err = err.Add_Comment(' ');
err = err.Add_Comment(['The integrand must have the following format:']);
err = err.Add_Comment(' ');
err = err.Add_Comment([' term #1 + term #2 + term #3 + ...']);
err = err.Add_Comment(' ');
err = err.Add_Comment(['where each "term" includes a single occurrence of a Test function.']);
err = err.Add_Comment(['Otherwise, the integrand is *not* a LINEAR form!']);
err.Error;
error('stop!');
end
end
end
function VALID = check_linearity(Integrand,Vars,FUNC)
% store these
%Sym_Zero = sym('0');
Sym_One = sym('1');
Sym_Two = sym('2');
subs_H = FEL_subs_handle();
% replace FUNC function with the constant 1 and 2 to check linear scaling
if ~isempty(FUNC)
% initialize
Sym_Integrand_One = Integrand;
Sym_Integrand_Two = Integrand;
for vi = 1:length(Vars)
MATCH = Var_Name_Matches_SymVar(FUNC,Vars(vi));
if MATCH
Sym_Integrand_One = subs_H(Sym_Integrand_One,Vars(vi),Sym_One);
Sym_Integrand_Two = subs_H(Sym_Integrand_Two,Vars(vi),Sym_Two);
end
end
% make sure it scales linearly
DIFF = simplify(2*Sym_Integrand_One - Sym_Integrand_Two,10);
% Note: if it is linear, then DIFF should be 0 (i.e. contains no symbolic variables).
SV = symvar(DIFF);
if isempty(SV)
VALID = (double(DIFF)==0); % should be zero if it is linear!
else
VALID = false; % DIFF must still contain some symbolic variables...
end
else
VALID = true;
end
end
|
github
|
eardi/sm-fpca-master
|
Verify_Consistent_Function_Domains.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Level_1/@abstractexpr/Verify_Consistent_Function_Domains.m
| 1,794 |
utf_8
|
d2b40c0987726be01797df8e787f086b
|
function status = Verify_Consistent_Function_Domains(obj)
%Verify_Consistent_Function_Domains
%
% This checks that all functions (Test, Trial, and Coef(s)) stored in this object are
% suitably defined on the domain of evaluation.
%
% status = obj.Verify_Consistent_Function_Domains;
%
% status = 0, if routine completes successfully.
% Copyright (c) 05-25-2012, Shawn W. Walker
status = 0;
verify_func_domain(obj.TestF, obj.Domain);
verify_func_domain(obj.TrialF,obj.Domain);
verify_func_domain(obj.CoefF, obj.Domain);
end
function verify_func_domain(FUNC, Eval_Domain)
% make sure that one of two possible states is true:
% (1) the function is from a finite element space that is defined on the
% domain of evaluation.
% OR
% (2) the function is from a finite element space AND is *restricted* to the
% domain of evaluation.
Int_Domain_Name = Eval_Domain.Name;
for ind = 1:length(FUNC)
FUNC_Domain_of_Defn = FUNC(ind).Get_Domain_Of_Definition;
if ~strcmp(Int_Domain_Name,FUNC_Domain_of_Defn.Name)
err = FELerror;
err = err.Add_Comment(['The function ', FUNC(ind).Name, ' is defined on the domain: ', FUNC_Domain_of_Defn.Name]);
err = err.Add_Comment(['The domain of evaluation is: ', Int_Domain_Name]);
err = err.Add_Comment('Suggestion: when defining the function, specify the subdomain you want to evaluate it on.');
err = err.Add_Comment([' example: ', FUNC(ind).Name, ' = ', class(FUNC(ind)),...
'(', FUNC(ind).Element.Name, ',', Int_Domain_Name, ');']);
err = err.Add_Comment('All functions in the *expression* must be defined on the domain of evaluation!');
err.Error;
error('stop!');
end
end
end
|
github
|
eardi/sm-fpca-master
|
Parse_Vars_From_Given_Function.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Matrix_Assembly/Level_1/@abstractexpr/Parse_Vars_From_Given_Function.m
| 4,021 |
utf_8
|
34277b9f7b2e3610dc6689499589a23e
|
function Parsed_Func = Parse_Vars_From_Given_Function(obj,L1Func,Vars)
%Parse_Vars_From_Given_Function
%
% This takes a given list of symbolic variables, finds the ones that
% correspond to the given function, and returns a structure containing those
% function vars. Each row of the output structure corresponds to a specific
% tensor component, and contains symbolic representations of operators applied
% to the given function.
%
% Parsed_Func = obj.Parse_Vars_From_Given_Function(L1Func,Vars);
%
% L1Func = a Level 1 l1func object (i.e. Test, Trial, or Coef).
% Vars = array of sym (symbolic) objects.
%
% Parsed_Func = Nx1 cell array of sym row vectors. N = number of tensor
% components of L1Func. Each sym row vector contains several
% sym entries, each one represents a match between L1Func and
% one of the entries in the given 'Vars' list.
% Note: if the tuple size is [m, n], then N = m*n.
% Copyright (c) 03-24-2018, Shawn W. Walker
MATCH_STR.vv_tt = '_v[1-9][1-9]?_t([1-9])([1-9]?)\w*';
MATCH_STR.tt_div = '_t([1-9])([1-9]?)_div';
MATCH_STR.tt_scalar_curl = '_t([1-9])([1-9]?)_curl';
Num_Tuple = L1Func.Num_Tensor;
TEMP_Func = cell(Num_Tuple(1),Num_Tuple(2));
Num_Vars = length(Vars);
for vv = 1:Num_Vars
var_str = char(Vars(vv));
Match_EXPR = [L1Func.Name, MATCH_STR.vv_tt];
m = regexp(var_str, Match_EXPR, 'tokens');
if ~isempty(m)
m_match = regexp(var_str, Match_EXPR, 'match');
[ti_1, ti_2] = extract_tuple_index(var_str,Num_Tuple,m);
TEMP_Func{ti_1,ti_2} = [TEMP_Func{ti_1,ti_2}, sym(m_match)];
else
% check if it was the divergence...
Match_EXPR = [L1Func.Name, MATCH_STR.tt_div];
m = regexp(var_str, Match_EXPR, 'tokens');
if ~isempty(m)
m_match = regexp(var_str, Match_EXPR, 'match');
[ti_1, ti_2] = extract_tuple_index(var_str,Num_Tuple,m);
TEMP_Func{ti_1,ti_2} = [TEMP_Func{ti_1,ti_2}, sym(m_match)];
else
% check if it was the scalar curl...
Match_EXPR = [L1Func.Name, MATCH_STR.tt_scalar_curl];
m = regexp(var_str, Match_EXPR, 'tokens');
if ~isempty(m)
m_match = regexp(var_str, Match_EXPR, 'match');
[ti_1, ti_2] = extract_tuple_index(var_str,Num_Tuple,m);
TEMP_Func{ti_1,ti_2} = [TEMP_Func{ti_1,ti_2}, sym(m_match)];
else
% L1Func.Name
% var_str
% error('This variable was not identified!');
end
end
end
end
Parsed_Func = TEMP_Func(:); % collapse to linear index
% for kk = 1:length(Parsed_Func)
% Parsed_Func{kk}
% end
% Num_Vars = length(Vars);
% for ti_1 = 1:Num_Tuple(1)
% for ti_2 = 1:Num_Tuple(2)
% row_sym = [];
% for vv = 1:Num_Vars
% var_str = char(Vars(vv));
% Match_EXPR = [L1Func.Name, '_v[1-9][1-9]?_t', num2str(ti_1), num2str(ti_2), '\w*'];
% m = regexp(var_str, Match_EXPR, 'match');
% if ~isempty(m)
% row_sym = [row_sym, sym(m)];
% else
% % check if it was the divergence...
% Match_EXPR = [L1Func.Name, '_t', num2str(ti_1), num2str(ti_2), '_div'];
% m = regexp(var_str, Match_EXPR, 'match');
% if ~isempty(m)
% row_sym = [row_sym, sym(m)];
% end
% end
% end
% kk = ti_1 + (ti_2 - 1)*Num_Tuple(1); % k = i + (j-1)*m
% Parsed_Func{kk} = row_sym;
% end
% end
end
function [ti_1, ti_2] = extract_tuple_index(var_str,Num_Tuple,mm)
tt_ind = mm{1};
ti_1 = str2double(tt_ind{1});
if ~isempty(tt_ind{2})
ti_2 = str2double(tt_ind{2});
else
ti_2 = 1;
end
if or((ti_1 > Num_Tuple(1)),(ti_2 > Num_Tuple(2)))
var_str
error('Variable has a tuple index greater than what it is supposed to!');
end
end
|
github
|
eardi/sm-fpca-master
|
pt_search_unit_test_dirs.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Interpolation/pt_search_unit_test_dirs.m
| 1,491 |
utf_8
|
0da6eaaf9eb85a0687bdd57f5c980143
|
function Unit_Test_Dirs = pt_search_unit_test_dirs()
%pt_search_unit_test_dirs
%
% This outputs a list of directories containing the unit tests.
% Copyright (c) 05-07-2019, Shawn W. Walker
% get the main directory that this function is in!
MFN = mfilename('fullpath');
Main_Dir = fileparts(MFN);
% define unit test dirs
% init
Unit_Test_Dirs.str1 = fullfile(Main_Dir, 'Unit_Test', 'Point_Searches', 'Dim_1');
Unit_Test_Dirs.str2 = [];
Unit_Test_Dirs.str3 = [];
% next!
str1 = fullfile(Main_Dir, 'Unit_Test', 'Point_Searches', 'Dim_2');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Unit_Test', 'Point_Searches', 'Dim_2_Codim_1');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Unit_Test', 'Point_Searches', 'Dim_3');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Unit_Test', 'Point_Searches', 'TopDim_1_GeoDim_2');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Unit_Test', 'Point_Searches', 'TopDim_1_GeoDim_3');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Unit_Test', 'Point_Searches', 'TopDim_2_GeoDim_3');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
end
function New_Dirs = append_dir(Dirs,str1,str2,str3)
DS.str1 = str1;
DS.str2 = str2;
DS.str3 = str3;
Num = length(Dirs);
New_Dirs = Dirs; % init
New_Dirs(Num+1) = DS;
end
|
github
|
eardi/sm-fpca-master
|
interpolation_unit_test_dirs.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Interpolation/interpolation_unit_test_dirs.m
| 1,342 |
utf_8
|
413ea0d6cff377bb1d0afc6a870997c6
|
function Unit_Test_Dirs = interpolation_unit_test_dirs()
%interpolation_unit_test_dirs
%
% This outputs a list of directories containing the unit tests.
% Copyright (c) 05-07-2019, Shawn W. Walker
% get the main directory that this function is in!
MFN = mfilename('fullpath');
Main_Dir = fileparts(MFN);
% define unit test dirs
% init
Unit_Test_Dirs.str1 = fullfile(Main_Dir, 'Unit_Test', 'Dim_2', 'Flat_Domain');
Unit_Test_Dirs.str2 = [];
Unit_Test_Dirs.str3 = [];
% next!
str1 = fullfile(Main_Dir, 'Unit_Test', 'Dim_2', 'Hdiv');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Unit_Test', 'Dim_2', 'Mixed_Geometry');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Unit_Test', 'Dim_2', 'Symbolic_Constant');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Unit_Test', 'TopDim_1_GeoDim_3', 'Shape_Operator');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
str1 = fullfile(Main_Dir, 'Unit_Test', 'TopDim_2_GeoDim_3', 'Shape_Operator');
Unit_Test_Dirs = append_dir(Unit_Test_Dirs,str1,[],[]);
end
function New_Dirs = append_dir(Dirs,str1,str2,str3)
DS.str1 = str1;
DS.str2 = str2;
DS.str3 = str3;
Num = length(Dirs);
New_Dirs = Dirs; % init
New_Dirs(Num+1) = DS;
end
|
github
|
eardi/sm-fpca-master
|
Need_Orientation.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Interpolation/Level_3/@FELPointSearches/Need_Orientation.m
| 647 |
utf_8
|
1721234c0d8a17cb6d17bfbca0632fd2
|
function TF = Need_Orientation(obj)
%Need_Orientation
%
% This indicates if mesh orientation data is needed.
% Copyright (c) 06-26-2014, Shawn W. Walker
GeomFunc = obj.GeomFuncs.values;
% if an option has been set (in any geometric function) for orientation data,
% then return true!
TF = false; % init
for ind = 1:length(GeomFunc)
GF = GeomFunc{ind};
Opt = GF.Opt;
TF = orientation_present(Opt);
if TF
break;
end
end
end
function TF = orientation_present(Opt)
TF = false;
if isfield(Opt,'Orientation')
if Opt.Orientation
TF = true;
end
end
end
|
github
|
eardi/sm-fpca-master
|
Run_Conversion.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Interpolation/Main/@Interp_L1toL3/Run_Conversion.m
| 2,360 |
utf_8
|
3f020b3d031a14d4966a478a4bf38dcd
|
function [FS, FI, C_Codes, Elems_DoF_Allocation] = Run_Conversion(obj,Main_Dir,Snippet_Dir)
%Run_Conversion
%
% This converts INTERP (a Level 1 object) into Level 3 objects.
% Note: there is an intermediate Level 2 object (struct).
% Copyright (c) 01-25-2013, Shawn W. Walker
Domain_of_Expression_Info = obj.Setup_FELDomain;
% create an array of special basis function objects that know nothing about the
% global FE space except for its NAME; just local info (like the reference
% element). This array of objects will be stored within FELSpaces...
FS = obj.Setup_FELSpaces(Domain_of_Expression_Info);
% FELSpace contains one single set of FE spaces and an array of
% Integration_Domains (expression domains). For each Integration_Domain, a set
% of basis functions is stored that corresponds to the set of FE spaces. In addition,
% any coefficient functions, and extra geometric functions, are also stored in each
% Integration_Domain.
[FS, FI] = obj.Init_FELInterpolations(FS,Snippet_Dir);
% remove the parts of the FELSpaces that are not used!
FS = obj.Prune_BasisFunc(FS);
C_Codes = obj.Setup_C_Codes(Main_Dir);
% get collection of Finite Element Definition structs needed for generating
% automatic DoF allocation mex files
Elems_DoF_Allocation = FE_Space_Info_For_DoF_Allocation(obj.INTERP);
end
function ELEMS = FE_Space_Info_For_DoF_Allocation(INTERP)
ELEMS = containers.Map; % init
Num_Interp_Expr = length(INTERP.Interp_Expr);
for ii = 1:Num_Interp_Expr
% get current interpolation
IE = INTERP.Interp_Expr{ii};
if ~isempty(IE.CoefF)
% loop through all CoefF's
for kk = 1:length(IE.CoefF)
Specific_CoefF = IE.CoefF(kk);
% get the corresponding element
FE_Space_Name = Specific_CoefF.Element.Name;
Elem = Specific_CoefF.Element.Elem;
% only include the FE space if it is *not* a global constant
if ~strcmp(Elem.Transformation,'Constant_Trans')
ELEMS(FE_Space_Name) = Elem;
end
end
end
% below is not needed...
% if ~isempty(IE.GeoF)
% % get current element
% % REMOVE?
% ELEMS(IE.GeoF.Name) = IE.GeoF.Elem;
% end
end
% add in geometry
ELEMS(INTERP.GeoElem.Name) = INTERP.GeoElem.Elem;
end
|
github
|
eardi/sm-fpca-master
|
Check_Domains.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Interpolation/Main/@Interp_L1toL3/private/Check_Domains.m
| 1,360 |
utf_8
|
5b967847833790a36e382161ed942ceb
|
function status = Check_Domains(obj,DS)
%Check_Domains
%
% This just does some basic error checking.
% Copyright (c) 01-28-2013, Shawn W. Walker
status = 0;
% check hold-all domain
if ~isequal(DS.Hold_All,obj.INTERP.GeoElem.Domain)
disp('Data structures are inconsistent!');
error('This should not happen. Please report this bug!');
end
Num_Domains = length(DS.Domain_Of_Expression);
for ind = 1:Num_Domains
DoE = DS.Domain_Of_Expression(ind);
if strcmp(DoE.Domain.Name,DoE.Domain.Subset_Of)
disp(['ERROR: Domain of Expression: ', DoE.Domain.Name]);
error('Domain of Expression cannot be a subset of itself!');
end
sbr_check_domain(DoE.Domain,DS.Hold_All);
% check all embeddings domains
for ee=1:length(DoE.Embeddings)
sbr_check_domain(DoE.Embeddings(ee),DS.Hold_All);
end
end
end
function sbr_check_domain(Domain,Hold_All)
% check that the domain is a subset of the Hold_All domain
if ~or(strcmp(Domain.Name,Hold_All.Name),strcmp(Domain.Subset_Of,Hold_All.Name))
disp(['ERROR: problem with this Domain: ', Domain.Name]);
disp(['ERROR: it is not equal to the hold-all domain: ', Hold_All.Name]);
disp(['ERROR: AND it is not a *subset* of the hold-all domain.']);
error('ERROR: check your Domain definitions!');
end
end
|
github
|
eardi/sm-fpca-master
|
Prune_BasisFunc.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Interpolation/Main/@Interp_L1toL3/private/Prune_BasisFunc.m
| 1,465 |
utf_8
|
8065ea6972e78679badecab1d74cfb90
|
function FS = Prune_BasisFunc(obj,FS)
%Prune_BasisFunc
%
% This removes the basis functions that are not used by the set of CoefF(s).
% Copyright (c) 01-29-2013, Shawn W. Walker
for ii = 1:length(FS.Integration)
% find the FE spaces that are needed to evaluate the FEM interpolations
Coef_Funcs = FS.Integration(ii).CoefFunc.values;
Space_Names = get_spaces_for_DoE(Coef_Funcs);
BF_Set = FS.Integration(ii).BasisFunc.values;
for bi = 1:length(BF_Set)
Current_BF = BF_Set{bi};
% search through matrices to see if it is used
USED = verify_basisfunc_is_used(Space_Names,Current_BF);
% if it is NOT used, then remove it!
if ~USED
remove(FS.Integration(ii).BasisFunc, Current_BF.Space_Name);
end
end
end
end
function Space_Names = get_spaces_for_DoE(Coef_Funcs)
Map_Names = containers.Map; % init
% add in any spaces needed for coefficient functions
for ci = 1:length(Coef_Funcs)
Map_Names(Coef_Funcs{ci}.Space_Name) = Coef_Funcs{ci}.Space_Name;
end
Space_Names = Map_Names.keys; % just need a cell array of names
end
function USED = verify_basisfunc_is_used(Space_Names,BasisFunc)
USED = false; % init
%disp(['Current BasisFunc Space: ', BasisFunc.Space_Name]);
for ind = 1:length(Space_Names)
if strcmp(BasisFunc.Space_Name,Space_Names{ind})
USED = true;
break;
end
end
end
|
github
|
eardi/sm-fpca-master
|
Setup_FELGeoms.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Interpolation/Main/@Interp_L1toL3/private/Setup_FELGeoms.m
| 2,785 |
utf_8
|
a0b0fd2a3e98aadc2a1a59f7161141db
|
function FS = Setup_FELGeoms(obj,FS)
%Setup_FELGeoms
%
% This inits the GeomFunc Map container under FS.Integration(ind).GeomFunc.
% Copyright (c) 01-27-2014, Shawn W. Walker
Num_Distinct_Expression_Domains = length(FS.Integration);
for ind = 1:Num_Distinct_Expression_Domains
% geometry representation for the domain of expression
DoE_GF = FS.Integration(ind).DoI_Geom;
Current_Expression_Domain = FS.Integration(ind).DoI_Geom.Domain.Integration_Domain;
% look thru all the matrices
Num_Expr = length(obj.INTERP.Interp_Expr);
for ie = 1:Num_Expr
%ID = obj.MATS.Matrix_Data{mi}.Integral;
I_Expr = obj.INTERP.Interp_Expr{ie};
% if the expression domain matches the current Expression_Domain
if isequal(I_Expr.Domain,Current_Expression_Domain)
% include any coefficient functions
for gi = 1:length(I_Expr.GeoF)
% get the domain we are interested in
Extra_Geom_Domain = I_Expr.GeoF(gi).Domain;
% create the object
GF = create_valid_extra_geom_func(DoE_GF,Extra_Geom_Domain);
if ~isempty(GF)
Geom_Domain_Name = GF.Domain.Subdomain.Name;
FS.Integration(ind).GeomFunc(Geom_Domain_Name) = GF; % insert!
end
end
end
end
end
% note: don't worry if a GeometricElementFunction gets overwritten; they are
% all on the same domain of expression!
end
function GeomFunc = create_valid_extra_geom_func(DoE_Geom,Extra_Geom_Domain)
%
% This creates a GeometricElementFunction for the domain of expression with
% respect to containment in the domain for which we want geometric information, i.e.
% the Subdomain.
%
% New_Domain.Global = global mesh domain.
% New_Domain.Subdomain = domain corresponding to the geometric data
% that we are interested in.
% New_Domain.Integration_Domain = where to evaluate the geometric data.
%
% Note: DoE_Geom is the geometric function representing the geometry of
% the Global mesh/domain and how the domain of expression is embedded.
% Copyright (c) 01-23-2014, Shawn W. Walker
New_Domain = DoE_Geom.Domain; % init
% set the Subdomain to be the domain where the geometric data is
New_Domain.Subdomain = Extra_Geom_Domain;
Extra_Geom_Domain_TopDim = Extra_Geom_Domain.Top_Dim;
DoE_TopDim = New_Domain.Integration_Domain.Top_Dim;
if (DoE_TopDim > Extra_Geom_Domain_TopDim)
% this is not a valid domain embedding, so return NULL
GeomFunc = [];
else
GeomFunc = GeometricElementFunction(DoE_Geom.Elem,New_Domain);
end
end
|
github
|
eardi/sm-fpca-master
|
Setup_FELSpaces.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Interpolation/Main/@Interp_L1toL3/private/Setup_FELSpaces.m
| 1,969 |
utf_8
|
687a1cb873788515d503e3cb6fd9a23c
|
function FS = Setup_FELSpaces(obj,Domain_Info)
%Setup_FELSpaces
%
% This inits the FELSpaces object.
% Copyright (c) 01-28-2013, Shawn W. Walker
check_geometric_element_domain_geodim_consistency(obj.INTERP.GeoElem.Tensor_Comp,Domain_Info);
% create geometric element for the Hold-All container domain
DEBUG = true;
Geom_Elem = ReferenceFiniteElement(obj.INTERP.GeoElem.Elem,DEBUG);
% initialize
FS = FELSpaces(Domain_Info,Geom_Elem);
% get unique list of FEM spaces
MAP = containers.Map();
Num_Expr = length(obj.INTERP.Interp_Expr);
for ind = 1:Num_Expr
I_Expr = obj.INTERP.Interp_Expr{ind};
for ci = 1:length(I_Expr.CoefF)
MAP = Insert_Element_Struct_Into_MAP(I_Expr.CoefF(ci).Element,MAP);
end
end
% append those spaces
FS_cell = MAP.values;
for ind = 1:length(FS_cell)
FS_struct = FS_cell{ind};
REF_ELEM = ReferenceFiniteElement(FS_struct.Elem,DEBUG);
FS = FS.Append_FEM_Space(FS_struct.Domain,FS_struct.Space_Name,REF_ELEM,FS_struct.Tensor_Comp);
end
% include any coefficient functions
FS = obj.Setup_FELCoefs(FS);
% include any extra geometric functions
FS = obj.Setup_FELGeoms(FS);
end
function check_geometric_element_domain_geodim_consistency(Tensor_Comp,Domain_Array)
% make sure there is consistency in the geometric dimension
for kk = 1:length(Domain_Array)
Domain_GD = Domain_Array(kk).Integration_Domain.GeoDim;
if (Tensor_Comp~=Domain_GD)
err = FELerror;
err = err.Add_Comment(['The ', 'Geometric', ' Element space does not have the']);
err = err.Add_Comment('same vector dimension as the Domain of Integration.');
err = err.Add_Comment(['Element space has dim = ', num2str(Tensor_Comp)]);
err = err.Add_Comment(['Domain of Integration has dim = ', num2str(Domain_GD)]);
err = err.Add_Comment('Check your Domain definitions!');
err.Error;
error('stop!');
end
end
end
|
github
|
eardi/sm-fpca-master
|
Get_Unique_List_Of_Domains.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Interpolation/Main/@Interp_L1toL3/private/Get_Unique_List_Of_Domains.m
| 4,247 |
utf_8
|
da83ba9c50ab0b76828f659d07ea8b05
|
function SS = Get_Unique_List_Of_Domains(obj)
%Get_Unique_List_Of_Domains
%
% This outputs a structure that looks like:
% SS.Hold_All = Global container domain.
% SS.Domain_Of_Expression(k).
% Domain = expression domain (that is embedded in Hold_All
% domain).
% Embeddings(j) = array of other domains that contain the
% expression domain. These embeddings will
% need to be computed elsewhere (when the
% mesh data is known).
% Copyright (c) 01-28-2013, Shawn W. Walker
% this is THE GLOBAL container set; there should only be one of these no matter
% how many subdomains or domains of expression there are!
SS.Hold_All = obj.INTERP.GeoElem.Domain;
% find all domains of expressions first
Domains_Of_Expression = containers.Map();
for ie=1:length(obj.INTERP.Interp_Expr)
I_Expr = obj.INTERP.Interp_Expr{ie};
Expr_Dom = I_Expr.Domain;
if ismember(Expr_Dom.Name,Domains_Of_Expression.keys)
% if that domain was used before, then make sure it did not change!
if ~isequal(Expr_Dom,Domains_Of_Expression(Expr_Dom.Name))
% if it doesn't match, then the user was doing things he shouldn't!
disp(['ERROR: This Domain was redefined: ', Expr_Dom.Name]);
error('You should not redefine a Domain!');
end
else
Domains_Of_Expression(Expr_Dom.Name) = Expr_Dom;
end
end
List_Of_Dom_Names = Domains_Of_Expression.keys;
% store the Domain of Expression
SS.Domain_Of_Expression = create_domain_of_expression_struct(obj,Domains_Of_Expression(List_Of_Dom_Names{1}));
for ind = 2:length(List_Of_Dom_Names)
% store the Domain of Expression
SS.Domain_Of_Expression(ind) = create_domain_of_expression_struct(obj,Domains_Of_Expression(List_Of_Dom_Names{ind}));
end
% SS
% SS.Domain_Of_Expression(1)
% %SS.Domain_Of_Expression(2)
% disp('==========================');
% SS.Domain_Of_Expression(1).Domain
% %SS.Domain_Of_Expression(2).Domain
% disp('==========================');
% SS.Domain_Of_Expression(1).Embeddings
% %SS.Domain_Of_Expression(2).Embeddings
% safdsafd
end
function DOE = create_domain_of_expression_struct(obj,Single_Domain_Of_Expression)
% this returns a struct:
% DOE.Domain
% DOE.Embeddings(k)
% the DOE.Embeddings(k) is a level 1 Domain that contains the DoE.
%
% So, for every coefficient function, we need to know that
% the Domain of Expression (DoE) is contained in the domain of definition of
% the function (i.e. we need to know to evaluate the function on a subset (DoE)
% of its domain of definition). This routine records that in the Embeddings
% struct/field. In other words, the Embeddings array contains all domains of
% definition (of the functions) that contain the DoE.
% store the Domain of Expression
DOE.Domain = Single_Domain_Of_Expression;
Embed = containers.Map(); % init
for ie=1:length(obj.INTERP.Interp_Expr)
I_Expr = obj.INTERP.Interp_Expr{ie};
if isequal(I_Expr.Domain,Single_Domain_Of_Expression)
Embed = get_function_domain(Embed, I_Expr.CoefF, DOE.Domain);
end
end
% put into the struct
if ~isempty(Embed)
keys = Embed.keys;
DOE.Embeddings = Embed(keys{1});
for kk = 2:length(keys)
DOE.Embeddings(kk) = Embed(keys{kk});
end
else
DOE.Embeddings = []; % no additional embeddings are needed
end
end
function Embed = get_function_domain(Embed, FUNC, DOE_Domain)
for ind = 1:length(FUNC)
% only need to add this functions domain of defn if it is different than the
% DoE
if ~isequal(FUNC(ind).Element.Domain,DOE_Domain)
% error check: make sure we are only dealing with functions that are
% being *evaluated* on the DOE_Domain
if ~isequal(FUNC(ind).Domain,DOE_Domain)
error('Function (in expression) must be evaluated on the domain of expression!');
end
% store the domain of defn of the function
Embed(FUNC(ind).Element.Domain.Name) = FUNC(ind).Element.Domain;
end
end
end
|
github
|
eardi/sm-fpca-master
|
Gen_Point_Search_Specific_cc.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Interpolation/Main/@GenFELPtSearchCode/Gen_Point_Search_Specific_cc.m
| 19,393 |
utf_8
|
5ef8bc2c5a51731290830e1e0993a72c
|
function Gen_Point_Search_Specific_cc(obj,FPS,Search_Domain)
%Gen_Point_Search_Specific_cc
%
% This generates the file: "CLASS_Search_SPECIFIC.cc", except with a more
% specific filename!
% Copyright (c) 07-26-2014, Shawn W. Walker
ENDL = '\n';
% get specific domain search information
CPP_PTS = FPS.Get_CPP_Point_Search_Vars(Search_Domain.Name);
% start with A part
File1 = [CPP_PTS.Search_Obj_CPP_Type, '.cc'];
WRITE_File = fullfile(obj.Output_Dir, obj.Sub_Dir.Point_Search_Classes, File1);
FEL_CopyFile(fullfile(obj.Skeleton_Dir, 'Point_Search_Specific_A.cc'),WRITE_File);
% open file for writing
fid = fopen(WRITE_File, 'a');
% EXAMPLE:
%%%%%%%
% /*------------ BEGIN: Auto Generate ------------*/
% // This class finds points (i.e. their enclosing cell index and local reference coordinates)
% // in this domain: Omega,
% // with topological dimension = 2
% // and geometric dimension = 2
% /*------------ END: Auto Generate ------------*/
% output text-lines
fprintf(fid, [obj.BEGIN_Auto_Gen, ENDL]);
fprintf(fid, ['// This class finds points (i.e. their enclosing cell index and local reference coordinates)', ENDL]);
fprintf(fid, ['// in this domain: ', Search_Domain.Name, ',', ENDL]);
fprintf(fid, ['// with topological dimension = ', num2str(Search_Domain.Top_Dim), ENDL]);
fprintf(fid, ['// and geometric dimension = ', num2str(Search_Domain.GeoDim), ENDL]);
fprintf(fid, [obj.END_Auto_Gen, ENDL]);
fprintf(fid, ['', ENDL]);
%%%%%%%
% EXAMPLE:
%%%%%%%
% /*------------ BEGIN: Auto Generate ------------*/
% // define the name of the search domain (should be the same as the filename of this file)
% #define SpecificSEARCH CLASS_Search_Omega
% #define SpecificSEARCH_str "CLASS_Search_Omega"
% /*------------ END: Auto Generate ------------*/
% get geometric function for the current search domain
GF = FPS.GeomFuncs(Search_Domain.Name);
TD = Search_Domain.Top_Dim();
Num_V = TD + 1;
Degree_Estimate = round(GF.Elem.Num_Basis / Num_V);
Num_Intermediate_Pts = 2 * Degree_Estimate - 1;
if strncmpi(GF.Elem.Element_Name,'lagrange_deg1',13)
% when each cell is linear, we do not need to evaluate intermediate points
Num_Intermediate_Pts = 0;
LINEAR = true;
else
LINEAR = false;
end
[Pound_Defines, C_Proto, Append_FileName] = get_c_code_bits(Search_Domain,Num_Intermediate_Pts,LINEAR);
% output text-lines
fprintf(fid, [obj.BEGIN_Auto_Gen, ENDL]);
fprintf(fid, ['// define the name of the search domain (should be the same as the filename of this file)', ENDL]);
fprintf(fid, ['#define SpecificSEARCH ', CPP_PTS.Search_Obj_CPP_Type, ENDL]);
fprintf(fid, ['#define SpecificSEARCH_str "', CPP_PTS.Search_Obj_CPP_Type, '"', ENDL]);
fprintf(fid, ['', ENDL]);
% define a bunch of tolerance and max iter stuff...
if ~isempty(Pound_Defines)
fprintf(fid, ['// define optimization parameters', ENDL]);
end
for ind = 1:length(Pound_Defines)
fprintf(fid, [Pound_Defines(ind).def, ENDL]);
end
fprintf(fid, [obj.END_Auto_Gen, ENDL]);
fprintf(fid, ['', ENDL]);
%%%%%%%
fprintf(fid, ['/***************************************************************************************/', ENDL]);
fprintf(fid, ['/* C++ (Specific) Point Search class */', ENDL]);
fprintf(fid, ['class SpecificSEARCH: public Mesh_Point_Search_Class // derive from base class', ENDL]);
fprintf(fid, ['{', ENDL]);
fprintf(fid, ['public:', ENDL]);
fprintf(fid, ['', ENDL]);
% EXAMPLE:
%%%%%%%
% /*------------ BEGIN: Auto Generate ------------*/
% // access and compute domain embedding info
% CLASS_Domain_Omega_embedded_in_Omega_restricted_to_Omega* Domain;
% /*------------ END: Auto Generate ------------*/
% output text-lines
fprintf(fid, [' ', obj.BEGIN_Auto_Gen, ENDL]);
fprintf(fid, [' ', '// access and compute domain embedding info', ENDL]);
Domain_CPP = GF.Domain.Determine_CPP_Info;
fprintf(fid, [' ', Domain_CPP.Data_Type_Name, '* ',...
'Domain', ';', ENDL]);
fprintf(fid, [' ', obj.END_Auto_Gen, ENDL]);
fprintf(fid, ['', ENDL]);
%%%%%%%
% EXAMPLE:
%%%%%%%
% /*------------ BEGIN: Auto Generate ------------*/
% // access and compute local mesh geometry info
% CLASS_geom_Omega_embedded_in_Omega_restricted_to_Omega* GeomFunc;
% /*------------ END: Auto Generate ------------*/
% output text-lines
fprintf(fid, [' ', obj.BEGIN_Auto_Gen, ENDL]);
fprintf(fid, [' ', '// access and compute local mesh geometry info', ENDL]);
fprintf(fid, [' ', GF.CPP.Data_Type_Name, '* ',...
'GeomFunc', ';', ENDL]);
fprintf(fid, [' ', obj.END_Auto_Gen, ENDL]);
fprintf(fid, ['', ENDL]);
%%%%%%%
% EXAMPLE:
%%%%%%%
% this will write the pre-declarations
fprintf(fid, [' ', obj.BEGIN_Auto_Gen, ENDL]);
fprintf(fid, [' ', '// constructor', ENDL]);
CONSTRUCTOR_STR = ['SpecificSEARCH (const Subdomain_Search_Data_Class*, Unstructured_Local_Points_Class*);'];
fprintf(fid, [' ', CONSTRUCTOR_STR, ENDL]);
fprintf(fid, [' ', '~SpecificSEARCH (); // destructor', ENDL]);
fprintf(fid, [' ', 'void Consistency_Check();', ENDL]);
% write routines that are specific to the search domain's topological and geometric dimension!
for ind = 1:length(C_Proto)
fprintf(fid, [' ', C_Proto(ind).func_prototype, ENDL]);
end
fprintf(fid, [' ', obj.END_Auto_Gen, ENDL]);
fprintf(fid, ['', 'private:', ENDL]);
fprintf(fid, ['};', ENDL]);
fprintf(fid, ['', ENDL]);
%%%%%%%
% append the next part
Fixed_File = fullfile(obj.Skeleton_Dir, 'Point_Search_Specific_B.cc');
status = obj.Append_ASCII_File_To_Open_File(Fixed_File,fid);
% now append file that is specific to the search domain's topological and geometric dimension!
Fixed_File = fullfile(obj.Skeleton_Dir, Append_FileName);
status = obj.Append_ASCII_File_To_Open_File(Fixed_File,fid);
fprintf(fid, ['', '// remove those macros!', ENDL]);
fprintf(fid, ['', '#undef SpecificSEARCH', ENDL]);
fprintf(fid, ['', '#undef SpecificSEARCH_str', ENDL]);
fprintf(fid, ['', '', ENDL]);
for ind = 1:length(Pound_Defines)
fprintf(fid, [Pound_Defines(ind).undef, ENDL]);
end
if ~isempty(Pound_Defines)
fprintf(fid, ['', '', ENDL]);
end
fprintf(fid, ['', '/***/', ENDL]);
% DONE!
fclose(fid);
end
function [Pound_Defines, C_Proto, Append_FileName] =...
get_c_code_bits(Search_Domain,Num_Intermediate_Pts,LINEAR)
TopDim = Search_Domain.Top_Dim;
GeoDim = Search_Domain.GeoDim;
% the #defines depend on the search domain
% the function prototypes depend on the topological and geometric dimension
% of the search domain
Pound_Defines.def = []; % init
Pound_Defines.undef = []; % init
C_Proto.func_prototype = []; % init
if (TopDim==1)
if (GeoDim==1) % TopDim=GeoDim
Pound_Defines(4).def = []; % init
Pound_Defines(1).def = '#define NEWTON_TOL 1E-13';
Pound_Defines(1).undef = '#undef NEWTON_TOL';
Pound_Defines(2).def = '#define REF_CELL_TOL 1E-12';
Pound_Defines(2).undef = '#undef REF_CELL_TOL';
Pound_Defines(3).def = '#define PT_DATA_TOPDIM_GEODIM_TYPE PT_DATA_Top1_Geo1';
Pound_Defines(3).undef = '#undef PT_DATA_TOPDIM_GEODIM_TYPE';
Pound_Defines(4).def = '#define VEC_DIM_TYPE VEC_1x1';
Pound_Defines(4).undef = '#undef VEC_DIM_TYPE';
if LINEAR
Pound_Defines(5).def = '#define LINEAR_CELL'; % faster min finding can be used here
Pound_Defines(5).undef = '#undef LINEAR_CELL';
end
C_Proto(3).func_prototype = []; % init
C_Proto(1).func_prototype = 'void Find_Points();';
C_Proto(2).func_prototype = 'bool Find_Single_Point(PT_DATA_Top1_Geo1&);';
C_Proto(3).func_prototype = 'int One_Iteration(PT_DATA_Top1_Geo1&);';
Append_FileName = 'Point_Search_Specific_TopDim_EQUAL_GeoDim.cc';
elseif (GeoDim==2)
Pound_Defines(8).def = []; % init
Pound_Defines(1).def = ['#define NUM_INTERMEDIATE_PTS ', num2str(Num_Intermediate_Pts)];
Pound_Defines(1).undef = '#undef NUM_INTERMEDIATE_PTS';
Pound_Defines(2).def = '#define OPT_TOL 1E-8';
Pound_Defines(2).undef = '#undef OPT_TOL';
Pound_Defines(3).def = '#define BIAS_TOL 0.25'; % positive and smaller than 0.5
Pound_Defines(3).undef = '#undef BIAS_TOL';
Pound_Defines(4).def = '#define MAX_QUEUE_SIZE 200';
Pound_Defines(4).undef = '#undef MAX_QUEUE_SIZE';
Pound_Defines(5).def = '#define MAX_LINE_SEARCH_ITER 300';
Pound_Defines(5).undef = '#undef MAX_LINE_SEARCH_ITER';
Pound_Defines(6).def = '#define PT_DATA_TOPDIM_GEODIM_TYPE PT_DATA_Top1_Geo2';
Pound_Defines(6).undef = '#undef PT_DATA_TOPDIM_GEODIM_TYPE';
Pound_Defines(7).def = '#define VEC_DIM_TYPE VEC_2x1';
Pound_Defines(7).undef = '#undef VEC_DIM_TYPE';
Pound_Defines(8).def = '#define MAT_DIM_TYPE MAT_2x1';
Pound_Defines(8).undef = '#undef MAT_DIM_TYPE';
if LINEAR
Pound_Defines(9).def = '#define LINEAR_CELL'; % faster min finding can be used here
Pound_Defines(9).undef = '#undef LINEAR_CELL';
end
C_Proto(14).func_prototype = []; % init
C_Proto( 1).func_prototype = 'void Find_Points();';
C_Proto( 2).func_prototype = 'bool Get_Valid_Neighbor(unsigned int&, const int&,';
C_Proto( 3).func_prototype = ' const unsigned int*, const unsigned int&);';
C_Proto( 4).func_prototype = 'bool Find_Single_Point(PT_DATA_Top1_Geo2&);';
C_Proto( 5).func_prototype = 'bool Find_Single_Point_Sub_Iter(const VEC_2x1&, unsigned int&,';
C_Proto( 6).func_prototype = ' unsigned int*, unsigned int&,';
C_Proto( 7).func_prototype = ' Min_On_Cell_Top1&, int&);';
C_Proto( 8).func_prototype = 'void Compute_Min_On_Interval(const VEC_2x1&, const unsigned int&,';
C_Proto( 9).func_prototype = ' unsigned int*, unsigned int&,';
C_Proto(10).func_prototype = ' Min_On_Cell_Top1&, int&);';
C_Proto(11).func_prototype = 'double Eval_Cost(const VEC_2x1&, const VEC_1x1&);';
C_Proto(12).func_prototype = 'void Eval_Cost_And_Gradient(const VEC_2x1&, const VEC_1x1&, SCALAR&, VEC_1x1&);';
C_Proto(13).func_prototype = 'void Bisection_And_Cubic_Line_Search(const VEC_2x1&, const unsigned int&,';
C_Proto(14).func_prototype = ' const double&, Min_On_Cell_Top1&, Min_On_Cell_Top1&);';
Append_FileName = 'Point_Search_Specific_TopDim1_GeoDim2or3.cc';
elseif (GeoDim==3)
Pound_Defines(8).def = []; % init
Pound_Defines(1).def = ['#define NUM_INTERMEDIATE_PTS ', num2str(Num_Intermediate_Pts)];
Pound_Defines(1).undef = '#undef NUM_INTERMEDIATE_PTS';
Pound_Defines(2).def = '#define OPT_TOL 1E-8';
Pound_Defines(2).undef = '#undef OPT_TOL';
Pound_Defines(3).def = '#define BIAS_TOL 0.25'; % positive and smaller than 0.5
Pound_Defines(3).undef = '#undef BIAS_TOL';
Pound_Defines(4).def = '#define MAX_QUEUE_SIZE 200';
Pound_Defines(4).undef = '#undef MAX_QUEUE_SIZE';
Pound_Defines(5).def = '#define MAX_LINE_SEARCH_ITER 300';
Pound_Defines(5).undef = '#undef MAX_LINE_SEARCH_ITER';
Pound_Defines(6).def = '#define PT_DATA_TOPDIM_GEODIM_TYPE PT_DATA_Top1_Geo3';
Pound_Defines(6).undef = '#undef PT_DATA_TOPDIM_GEODIM_TYPE';
Pound_Defines(7).def = '#define VEC_DIM_TYPE VEC_3x1';
Pound_Defines(7).undef = '#undef VEC_DIM_TYPE';
Pound_Defines(8).def = '#define MAT_DIM_TYPE MAT_3x1';
Pound_Defines(8).undef = '#undef MAT_DIM_TYPE';
if LINEAR
Pound_Defines(9).def = '#define LINEAR_CELL'; % faster min finding can be used here
Pound_Defines(9).undef = '#undef LINEAR_CELL';
end
C_Proto(14).func_prototype = []; % init
C_Proto( 1).func_prototype = 'void Find_Points();';
C_Proto( 2).func_prototype = 'bool Get_Valid_Neighbor(unsigned int&, const int&,';
C_Proto( 3).func_prototype = ' const unsigned int*, const unsigned int&);';
C_Proto( 4).func_prototype = 'bool Find_Single_Point(PT_DATA_Top1_Geo3&);';
C_Proto( 5).func_prototype = 'bool Find_Single_Point_Sub_Iter(const VEC_3x1&, unsigned int&,';
C_Proto( 6).func_prototype = ' unsigned int*, unsigned int&,';
C_Proto( 7).func_prototype = ' Min_On_Cell_Top1&, int&);';
C_Proto( 8).func_prototype = 'void Compute_Min_On_Interval(const VEC_3x1&, const unsigned int&,';
C_Proto( 9).func_prototype = ' unsigned int*, unsigned int&,';
C_Proto(10).func_prototype = ' Min_On_Cell_Top1&, int&);';
C_Proto(11).func_prototype = 'double Eval_Cost(const VEC_3x1&, const VEC_1x1&);';
C_Proto(12).func_prototype = 'void Eval_Cost_And_Gradient(const VEC_3x1&, const VEC_1x1&, SCALAR&, VEC_1x1&);';
C_Proto(13).func_prototype = 'void Bisection_And_Cubic_Line_Search(const VEC_3x1&, const unsigned int&,';
C_Proto(14).func_prototype = ' const double&, Min_On_Cell_Top1&, Min_On_Cell_Top1&);';
Append_FileName = 'Point_Search_Specific_TopDim1_GeoDim2or3.cc';
else
error('Invalid!');
end
elseif (TopDim==2)
if (GeoDim==2) % TopDim=GeoDim
Pound_Defines(4).def = []; % init
Pound_Defines(1).def = '#define NEWTON_TOL 1E-13';
Pound_Defines(1).undef = '#undef NEWTON_TOL';
Pound_Defines(2).def = '#define REF_CELL_TOL 1E-12';
Pound_Defines(2).undef = '#undef REF_CELL_TOL';
Pound_Defines(3).def = '#define PT_DATA_TOPDIM_GEODIM_TYPE PT_DATA_Top2_Geo2';
Pound_Defines(3).undef = '#undef PT_DATA_TOPDIM_GEODIM_TYPE';
Pound_Defines(4).def = '#define VEC_DIM_TYPE VEC_2x1';
Pound_Defines(4).undef = '#undef VEC_DIM_TYPE';
if LINEAR
Pound_Defines(5).def = '#define LINEAR_CELL'; % faster min finding can be used here
Pound_Defines(5).undef = '#undef LINEAR_CELL';
end
C_Proto(3).func_prototype = []; % init
C_Proto(1).func_prototype = 'void Find_Points();';
C_Proto(2).func_prototype = 'bool Find_Single_Point(PT_DATA_Top2_Geo2&);';
C_Proto(3).func_prototype = 'int One_Iteration(PT_DATA_Top2_Geo2&);';
Append_FileName = 'Point_Search_Specific_TopDim_EQUAL_GeoDim.cc';
elseif (GeoDim==3)
Pound_Defines(6).def = []; % init
Pound_Defines(1).def = ['#define NUM_INTERMEDIATE_PTS ', num2str(Num_Intermediate_Pts)];
Pound_Defines(1).undef = '#undef NUM_INTERMEDIATE_PTS';
Pound_Defines(2).def = '#define OPT_TOL 1E-8';
Pound_Defines(2).undef = '#undef OPT_TOL';
Pound_Defines(3).def = '#define BIAS_TOL 0.25'; % positive and smaller than 0.5
Pound_Defines(3).undef = '#undef BIAS_TOL';
Pound_Defines(4).def = '#define MAX_QUEUE_SIZE 200';
Pound_Defines(4).undef = '#undef MAX_QUEUE_SIZE';
Pound_Defines(5).def = '#define MAX_GRADIENT_DESCENT_ITER 500';
Pound_Defines(5).undef = '#undef MAX_GRADIENT_DESCENT_ITER';
Pound_Defines(6).def = '#define MAX_LINE_SEARCH_ITER 300';
Pound_Defines(6).undef = '#undef MAX_LINE_SEARCH_ITER';
if LINEAR
Pound_Defines(7).def = '#define LINEAR_CELL'; % faster min finding can be used here
Pound_Defines(7).undef = '#undef LINEAR_CELL';
end
C_Proto(17).func_prototype = []; % init
C_Proto( 1).func_prototype = 'void Find_Points();';
C_Proto( 2).func_prototype = 'bool Get_Valid_Neighbor(unsigned int&, int&, const int&,';
C_Proto( 3).func_prototype = ' const unsigned int*, const unsigned int&);';
C_Proto( 4).func_prototype = 'bool Find_Single_Point(PT_DATA_Top2_Geo3&);';
C_Proto( 5).func_prototype = 'bool Find_Single_Point_Sub_Iter(const VEC_3x1& GX, unsigned int& ci,';
C_Proto( 6).func_prototype = ' unsigned int* ciq, unsigned int& qs,';
C_Proto( 7).func_prototype = ' Min_On_Cell_Top2& M, int ln[2]);';
C_Proto( 8).func_prototype = 'void Compute_Min_On_Triangle(const VEC_3x1& GX, const unsigned int& ci,';
C_Proto( 9).func_prototype = ' const int& asi, const int& pmsi,';
C_Proto(10).func_prototype = ' unsigned int* ciq, unsigned int& qs,';
C_Proto(11).func_prototype = ' Min_On_Cell_Top2& M, int ln[2]);';
C_Proto(12).func_prototype = 'bool Run_Gradient_Descent(const VEC_3x1&, Min_On_Cell_Top2&, const double&);';
C_Proto(13).func_prototype = 'double Eval_Cost(const VEC_3x1&, const VEC_2x1&);';
C_Proto(14).func_prototype = 'void Eval_Cost_And_Gradient(const VEC_3x1&, const VEC_2x1&, SCALAR&, VEC_2x1&);';
C_Proto(15).func_prototype = 'void Eval_Cost_And_Directional_Deriv(const VEC_3x1&, const VEC_2x1&, const VEC_2x1&, SCALAR&, SCALAR&);';
C_Proto(16).func_prototype = 'void Bisection_And_Cubic_Line_Search(const VEC_3x1&, const VEC_2x1&, const unsigned int&,';
C_Proto(17).func_prototype = ' const double&, Min_On_Cell_Top2&, Min_On_Cell_Top2&);';
Append_FileName = 'Point_Search_Specific_TopDim2_GeoDim3.cc';
else
error('Invalid!');
end
elseif (TopDim==3)
if (GeoDim==3) % TopDim=GeoDim
Pound_Defines(4).def = []; % init
Pound_Defines(1).def = '#define NEWTON_TOL 1E-13';
Pound_Defines(1).undef = '#undef NEWTON_TOL';
Pound_Defines(2).def = '#define REF_CELL_TOL 1E-12';
Pound_Defines(2).undef = '#undef REF_CELL_TOL';
Pound_Defines(3).def = '#define PT_DATA_TOPDIM_GEODIM_TYPE PT_DATA_Top3_Geo3';
Pound_Defines(3).undef = '#undef PT_DATA_TOPDIM_GEODIM_TYPE';
Pound_Defines(4).def = '#define VEC_DIM_TYPE VEC_3x1';
Pound_Defines(4).undef = '#undef VEC_DIM_TYPE';
if LINEAR
Pound_Defines(5).def = '#define LINEAR_CELL'; % faster min finding can be used here
Pound_Defines(5).undef = '#undef LINEAR_CELL';
end
C_Proto(3).func_prototype = []; % init
C_Proto(1).func_prototype = 'void Find_Points();';
C_Proto(2).func_prototype = 'bool Find_Single_Point(PT_DATA_Top3_Geo3&);';
C_Proto(3).func_prototype = 'int One_Iteration(PT_DATA_Top3_Geo3&);';
Append_FileName = 'Point_Search_Specific_TopDim_EQUAL_GeoDim.cc';
else
error('Invalid!');
end
else
error('Invalid!');
end
end
|
github
|
eardi/sm-fpca-master
|
Check_Domains.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Interpolation/Main/@PtSearch_L1toL3/private/Check_Domains.m
| 1,232 |
utf_8
|
a858da466ecc2d7458d16d88a7f474f4
|
function status = Check_Domains(obj,DS)
%Check_Domains
%
% This just does some basic error checking.
% Copyright (c) 06-13-2014, Shawn W. Walker
status = 0;
% check hold-all domain
if ~isequal(DS.Hold_All,obj.PTSEARCH.GeoElem.Domain)
disp('Data structures are inconsistent!');
error('This should not happen. Please report this bug!');
end
Num_Domains = length(DS.Domain_Of_Expression);
for ind = 1:Num_Domains
DoE = DS.Domain_Of_Expression(ind);
if strcmp(DoE.Domain.Name,DoE.Domain.Subset_Of)
disp(['ERROR: Domain of Expression: ', DoE.Domain.Name]);
error('Domain of Expression cannot be a subset of itself!');
end
sbr_check_domain(DoE.Domain,DS.Hold_All);
end
end
function sbr_check_domain(Domain,Hold_All)
% check that the domain is a subset of the Hold_All domain
if ~or(strcmp(Domain.Name,Hold_All.Name),strcmp(Domain.Subset_Of,Hold_All.Name))
disp(['ERROR: there is a problem with this Domain: ', Domain.Name]);
disp(['ERROR: it is not equal to the hold-all domain: ', Hold_All.Name]);
disp(['ERROR: AND it is not a *subset* of the hold-all domain.']);
error('ERROR: check your Domain definitions!');
end
end
|
github
|
eardi/sm-fpca-master
|
FEL_Execute_Interp_Shape_Op_2D.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Interpolation/Unit_Test/TopDim_2_GeoDim_3/Shape_Operator/FEL_Execute_Interp_Shape_Op_2D.m
| 3,167 |
utf_8
|
3b25928aa8a2bd58601717278f12a5eb
|
function status = FEL_Execute_Interp_Shape_Op_2D(mexName)
%FEL_Execute_Interp_Shape_Op_2D
%
% test FELICITY Auto-Generated Interpolation Code.
% Copyright (c) 08-16-2014, Shawn W. Walker
% current_file = mfilename('fullpath');
% Current_Dir = fileparts(current_file);
% get test mesh
[Omega_P1_Vtx, Omega_Tri] = Standard_Triangle_Mesh_Test_Data();
% domain is a square [0, 2] X [0, 2]
Mesh = MeshTriangle(Omega_Tri, Omega_P1_Vtx, 'Gamma');
% refine
for ind = 1:2
Mesh = Mesh.Refine;
end
% define other FE space stuff
P1_DoFmap = uint32(Mesh.ConnectivityList);
P2_DoFmap = uint32(Setup_Lagrange_P2_DoFmap(Mesh.ConnectivityList,[]));
% get P2_Lagrange Node coordinates
P2_RefElem = ReferenceFiniteElement(lagrange_deg2_dim2());
P2_Lagrange_Space = FiniteElementSpace('Scalar_P2', P2_RefElem, Mesh, 'Gamma');
P2_Lagrange_Space = P2_Lagrange_Space.Set_DoFmap(Mesh,uint32(P2_DoFmap));
P2_X = P2_Lagrange_Space.Get_DoF_Coord(Mesh);
% add the z-component
P2_X = [P2_X, 0*P2_X(:,1)];
% % make it a paraboloid
% P2_X(:,3) = 1 - P2_X(:,1).^2 - P2_X(:,2).^2;
% make it a sine wave
P2_X(:,3) = sin(2*pi*P2_X(:,1).*P2_X(:,2));
% define the interpolation points
Cell_Indices = (1:1:Mesh.Num_Cell)';
% interpolate at the barycenter of reference triangle
Gamma_Interp_Data = {uint32(Cell_Indices), (1/3) * ones(Mesh.Num_Cell,2)};
%BC = Mesh.refToBary(Gamma_Interp_Data{2});
%Interp_Pts = Mesh.baryToCart(Cell_Indices, BC);
% interpolate!
tic
INTERP = feval(str2func(mexName),P2_X,P2_DoFmap,[],[],Gamma_Interp_Data);
toc
kappa = INTERP(1).DATA{1};
kappa_G = INTERP(2).DATA{1};
Num_Pts = length(Gamma_Interp_Data{1});
NV = zeros(Num_Pts,3);
NV(:) = cell2mat(INTERP(3).DATA);
Shape_Op = zeros(3,3,Num_Pts);
for ii = 1:3
for jj = 1:3
Shape_Op(ii,jj,:) = INTERP(4).DATA{ii,jj};
end
end
% error check
CHK_NV = 0;
CHK_kappa = 0;
CHK_kappa_G = 0;
for pt = 1:Num_Pts
% get interpolated value at each point
kappa_pt = kappa(pt);
kappa_G_pt = kappa_G(pt);
NV_pt = NV(pt,:)';
Shape_Op_pt = Shape_Op(:,:,pt);
% check that the normal vector gets mapped to the zero vector
CHK_NV = max(max(abs(Shape_Op_pt * NV_pt)), CHK_NV);
% check the eigenvalues of the shape operator against the total and gauss curvatures
lambda = eig(Shape_Op_pt);
lambda = remove_smallest_mag_element(lambda);
CHK_kappa = max(abs(sum(lambda) - kappa_pt), CHK_kappa);
CHK_kappa_G = max(prod(lambda) - kappa_G_pt, CHK_kappa_G);
end
status = 0; % init
TOL = 1e-11;
if (CHK_NV > TOL)
CHK_NV
disp('Normal vector is not in the null space of the shape operator.');
status = 1;
end
if (CHK_kappa > TOL)
CHK_kappa
disp('Sum of the principle curvatures does not match the trace of the shape operator.');
status = 1;
end
if (CHK_kappa_G > TOL)
CHK_kappa_G
disp('Gaussian curvature does not match the product of the (non-zero) eigenvalues of the shape operator.');
status = 1;
end
end
function new_vec = remove_smallest_mag_element(vec)
[~, Ind] = min(abs(vec));
new_vec = vec;
new_vec(Ind) = [];
end
|
github
|
eardi/sm-fpca-master
|
FEL_Execute_Interp_BDM1_2D.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Interpolation/Unit_Test/Dim_2/Hdiv/FEL_Execute_Interp_BDM1_2D.m
| 3,908 |
utf_8
|
6fba7a850a5c03d3023c9d08e1494e44
|
function status = FEL_Execute_Interp_BDM1_2D(mexName_DoF,mexName_Interp)
%FEL_Execute_Interp_BDM1_2D
%
% test FELICITY Auto-Generated Interpolation Code.
% Copyright (c) 02-10-2013, Shawn W. Walker
current_file = mfilename('fullpath');
Current_Dir = fileparts(current_file);
% get test mesh
[Omega_P1_Vtx, Omega_Tri] = Standard_Triangle_Mesh_Test_Data();
% domain is a square [0, 2] X [0, 2]
Mesh = MeshTriangle(Omega_Tri, Omega_P1_Vtx, 'Omega');
% refine
for ind = 1:0
Mesh = Mesh.Refine;
end
% append the boundary as a subdomain
FBE = Mesh.freeBoundary;
Mesh = Mesh.Append_Subdomain('1D','Gamma',FBE);
% create edge orientation
Edges = Mesh.edges;
[Tri_Edge, Omega_Orient] = Mesh.Get_Facet_Info(Edges);
% a true entry means the local edge of the given triangle is contained in the
% Tri_Edge array; false means the *reversed* edge is in the Tri_Edge array.
% allocate DoFs
BDM1_DoFmap = feval(str2func(mexName_DoF),uint32(Mesh.ConnectivityList));
%Num_BDM1_Nodes = max(BDM1_DoFmap(:));
% create embedding data
DoE_Names = {'Gamma'; 'Omega'};
Omega_Mesh_Subdomains = Mesh.Generate_Subdomain_Embedding_Data(DoE_Names);
% BDM1 FE functions
F1 = @(X) [exp(-0.5*X(:,1).*X(:,2)), sin(pi*X(:,1).*X(:,2))];
v = Get_BDM1_Interpolant_of_Function(Mesh.Points,Mesh.ConnectivityList,BDM1_DoFmap,Omega_Orient,F1);
% exact interpolant functions
I_v = @(x,y) {exp(-0.5*x.*y);
sin(pi*x.*y)};
%
% define the interpolation points
Cell_Omega_Indices = (1:1:Mesh.Num_Cell)';
% interpolate at the barycenter of reference triangle (on Omega)
Omega_Interp_Data = {uint32(Cell_Omega_Indices), (1/3) * ones(Mesh.Num_Cell,2)};
Omega_Interp_Pts = Mesh.referenceToCartesian(Cell_Omega_Indices, Omega_Interp_Data{2});
% define the interpolation points
Mesh_Gamma = Mesh.Output_Subdomain_Mesh('Gamma');
Cell_Gamma_Indices = (1:1:Mesh_Gamma.Num_Cell)';
% interpolate at the barycenter of reference edge (on Gamma)
Gamma_Interp_Data = {uint32(Cell_Gamma_Indices), (1/2) * ones(Mesh_Gamma.Num_Cell,1)};
Gamma_Interp_Pts = Mesh_Gamma.referenceToCartesian(Cell_Gamma_Indices, Gamma_Interp_Data{2});
% interpolate!
tic
INTERP = feval(str2func(mexName_Interp),Mesh.Points,uint32(Mesh.ConnectivityList),Omega_Orient,Omega_Mesh_Subdomains,...
Gamma_Interp_Data,Omega_Interp_Data,BDM1_DoFmap,v);
toc
RefINTERPDataFileName = fullfile(Current_Dir,'FEL_Execute_Interp_BDM1_2D_REF_Data.mat');
% INTERP_REF = INTERP;
% save(RefINTERPDataFileName,'INTERP_REF');
load(RefINTERPDataFileName);
% compare the exact values with the interpolated ones
I_on_Gamma_exact = I_on_Gamma(Gamma_Interp_Pts(:,1),Gamma_Interp_Pts(:,2));
I_v_exact = I_v(Omega_Interp_Pts(:,1),Omega_Interp_Pts(:,2));
% these errors satisfy the order of accuracy estimates when refining...
I_on_Gamma_err = max(abs(I_on_Gamma_exact - INTERP(1).DATA{1,1}));
I_v1_err = max(abs(I_v_exact{1,1} - INTERP(2).DATA{1,1}));
I_v2_err = max(abs(I_v_exact{2,1} - INTERP(2).DATA{2,1}));
disp(' ');
disp('L_inf errors for the interpolations:');
I_on_Gamma_err
I_v1_err
I_v2_err
status = 0; % init
% compare to reference data
for ind = 1:length(INTERP)
[nr, nc] = size(INTERP(ind).DATA);
for ir = 1:nr
for ic = 1:nc
ERROR = max(abs(INTERP(ind).DATA{ir,ic} - INTERP_REF(ind).DATA{ir,ic}));
if (ERROR > 4e-15)
disp(['Test Failed for INTERP(', num2str(ind), ').DATA...']);
status = 1;
end
end
end
end
end
function Exact = I_on_Gamma(x,y)
v1 = exp(-0.5*x.*y);
v2 = sin(pi*x.*y);
LEFT = (x < 1e-10);
RIGHT = (x > (2-1e-10));
BOT = (y < 1e-10);
TOP = (y > (2-1e-10));
Exact = 0*x;
Exact(LEFT,1) = -v1(LEFT,1);
Exact(RIGHT,1) = v1(RIGHT,1);
Exact(BOT,1) = -v2(BOT,1);
Exact(TOP,1) = v2(TOP,1);
end
|
github
|
eardi/sm-fpca-master
|
FEL_Execute_Pt_Search_Curve_In_3D.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Interpolation/Unit_Test/Point_Searches/TopDim_1_GeoDim_3/FEL_Execute_Pt_Search_Curve_In_3D.m
| 4,813 |
utf_8
|
8ea863abb0b9ae60f2ff9f3debc156a0
|
function status = FEL_Execute_Pt_Search_Curve_In_3D(mexName)
%FEL_Execute_Pt_Search_Curve_In_3D
%
% test FELICITY Auto-Generated Point Search Code.
% Copyright (c) 07-25-2014, Shawn W. Walker
current_file = mfilename('fullpath');
Current_Dir = fileparts(current_file);
% get test mesh (interval [0, 9])
[Sigma_P1_Vtx, Sigma_Edge] = Standard_Edge_Mesh_Test_Data();
% add a y and z-component
y = 0*Sigma_P1_Vtx(:,1);
z = 0*Sigma_P1_Vtx(:,1);
Sigma_P1_Vtx = [Sigma_P1_Vtx, y, z];
Mesh = MeshInterval(Sigma_Edge, Sigma_P1_Vtx, 'Sigma');
% refine
for ind = 1:2
Mesh = Mesh.Refine;
end
% make a parabola
x = Mesh.Points(:,1);
y = 0.1*(20 - (x - 4.5).^2);
z = 0.1*(20 - (x - 4.5).^2);
Mesh = Mesh.Set_Points([Mesh.Points(:,1), y, z]);
% define the global points
% NP = 100000;
% % set some random global points
% rx = 9*rand(NP,1);
% ry = 2*rand(NP,1);
% rz = 2*rand(NP,1);
% GX = [rx, ry, rz];
[XX,YY,ZZ] = meshgrid((0:2:9)',(-1:0.7:1)',(-1:0.7:1)');
GX = [XX(:), YY(:), ZZ(:)];
clear XX YY ZZ;
Cell_Indices = uint32(ones(size(GX,1),1));
%Cell_Indices = uint32(randi(Mesh.Num_Cell,size(GX,1),1));
Sigma_Neighbors = uint32(Mesh.neighbors);
Sigma_Given_Points = {Cell_Indices, GX, Sigma_Neighbors};
% search!
tic
SEARCH = feval(str2func(mexName),Mesh.Points,uint32(Mesh.ConnectivityList),[],[],Sigma_Given_Points);
toc
RefSEARCHDataFileName = fullfile(Current_Dir,'FEL_Execute_Pt_Search_Curve_In_3D_REF_Data.mat');
% SEARCH_REF = SEARCH;
% save(RefSEARCHDataFileName,'SEARCH_REF');
load(RefSEARCHDataFileName);
status = 0; % init
if ~strcmp(SEARCH.Name,Mesh.Name)
disp('Domain name does not match!');
status = 1;
end
% get closest cell indices
CI = double(SEARCH.DATA{1});
if (min(CI) <= 0)
disp('At least one point was not found in the mesh!');
status = 1;
end
% get corresponding local reference triangle coordinates
Local_Ref_Coord = SEARCH.DATA{2};
N1 = 1 - sum(Local_Ref_Coord,2);
CHK = [N1, Local_Ref_Coord];
MIN_VAL = min(CHK(:));
MAX_VAL = max(CHK(:));
% make sure the coordinates are inside the ref triangle
if ~and(MIN_VAL >= -1e-15, MAX_VAL <= 1 + 1e-15)
disp('Some local points are outside reference triangle!');
status = 1;
end
% check that difference vector is "orthogonal" to the surface
XC = Mesh.referenceToCartesian(CI, Local_Ref_Coord);
Global_X = Sigma_Given_Points{2};
DIFF_VEC = Global_X - XC;
% look at some of the closest points
PT_Mask = (Global_X(:,1) > 1) & (Global_X(:,1) < 8);
%PT_Mask_Other = ~PT_Mask;
PTS_Closest_To_First_Vtx = [1, 2, 3, 16, 17, 31];
PTS_Closest_To_Last_Vtx = [13, 14, 28];
% compute edge vectors
Edges = Mesh.edges;
EV = Mesh.Points(Edges(:,2),:) - Mesh.Points(Edges(:,1),:);
UNIT_EV = normalize_vec(EV);
% check "orthogonality"
UNIT_DIFF_VEC = normalize_vec(DIFF_VEC);
CHK_ORTHO = dot(UNIT_EV(CI,:),UNIT_DIFF_VEC,2);
% only the ones in set A will be ortho
CHK_A = CHK_ORTHO(PT_Mask);
ORTHO_ERROR = max(abs(CHK_A));
if (ORTHO_ERROR > 1e-13)
ORTHO_ERROR
disp(['Orthogonality Test Failed for Point Searching...']);
status = 1;
end
% check that the other global points are closest to the ENDS of the parabola
XC_First = XC(PTS_Closest_To_First_Vtx,:);
First_Vtx = [0, -2.5e-02, -2.5e-02];
CHK_First = [XC_First(:,1) - First_Vtx(1), XC_First(:,2) - First_Vtx(2), XC_First(:,3) - First_Vtx(3)];
CHK_First_MAX = max(abs(CHK_First(:)));
XC_Last = XC(PTS_Closest_To_Last_Vtx,:);
Last_Vtx = [9, -2.5e-02, -2.5e-02];
CHK_Last = [XC_Last(:,1) - Last_Vtx(1), XC_Last(:,2) - Last_Vtx(2), XC_Last(:,3) - Last_Vtx(3)];
CHK_Last_MAX = max(abs(CHK_Last(:)));
if max(CHK_First_MAX,CHK_Last_MAX)
disp(['Global Points Not Close To End Points...']);
status = 1;
end
% plot closest points
figure;
Mesh.Plot;
hold on;
plot3(Global_X(:,1),Global_X(:,2),Global_X(:,3),'k*','MarkerSize',10);
plot3(XC(:,1),XC(:,2),XC(:,3),'r.','MarkerSize',20);
plot3([XC(:,1), Global_X(:,1)]',[XC(:,2), Global_X(:,2)]',[XC(:,3), Global_X(:,3)]','b-');
hold off;
axis([0 9 -1.5 2.5 -1.5 2.5]);
axis equal;
title('Closest Point Search On 3-D Curve Mesh');
% compare to reference data
for ind = 1:length(SEARCH)
ECI = max(abs(SEARCH(ind).DATA{1} - SEARCH_REF(ind).DATA{1}));
ELR = max(abs(SEARCH(ind).DATA{2} - SEARCH_REF(ind).DATA{2}));
if (ECI > 0)
disp(['Test Failed for SEARCH(', num2str(ind), ').DATA{1}...']);
status = 1;
end
if (ELR > 4e-15)
disp(['Test Failed for SEARCH(', num2str(ind), ').DATA{2}...']);
status = 1;
end
end
end
function UNIT_VEC = normalize_vec(VEC)
MAG0 = sqrt(sum(VEC.^2,2));
UNIT_VEC = VEC;
UNIT_VEC(:,1) = VEC(:,1) ./ MAG0;
UNIT_VEC(:,2) = VEC(:,2) ./ MAG0;
UNIT_VEC(:,3) = VEC(:,3) ./ MAG0;
end
|
github
|
eardi/sm-fpca-master
|
FEL_Execute_Pt_Search_Surface_In_3D.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Interpolation/Unit_Test/Point_Searches/TopDim_2_GeoDim_3/FEL_Execute_Pt_Search_Surface_In_3D.m
| 5,266 |
utf_8
|
260b1acd6cff744c6f32383e8da40541
|
function status = FEL_Execute_Pt_Search_Surface_In_3D(mexName)
%FEL_Execute_Pt_Search_Surface_In_3D
%
% test FELICITY Auto-Generated Point Search Code.
% Copyright (c) 07-24-2014, Shawn W. Walker
current_file = mfilename('fullpath');
Current_Dir = fileparts(current_file);
% get test mesh (square [0, 2] X [0, 2])
[Gamma_P1_Vtx, Gamma_Tri] = Standard_Triangle_Mesh_Test_Data();
%Gamma_Tri = Gamma_Tri(:,[3 1 2]);
% add a z-component
z = 0*Gamma_P1_Vtx(:,1);
Gamma_P1_Vtx = [Gamma_P1_Vtx, z];
Mesh = MeshTriangle(Gamma_Tri, Gamma_P1_Vtx, 'Gamma');
% refine
for ind = 1:0
Mesh = Mesh.Refine;
end
% make a quadratic surface
z = 1 - ( (Mesh.Points(:,1) - 1).^2 + (Mesh.Points(:,2) - 1).^2 );
Mesh = Mesh.Set_Points([Mesh.Points(:,1:2), z]);
% define the global points
% NP = 1000;
% % set some random global points
% rx = 2*rand(NP,1);
% ry = 2*rand(NP,1);
% %rz = 2*rand(NP,1);
% rz = 1.5 + 0.2*(rand(NP,1) - 0.5);
% GX = [rx, ry, rz];
s_vec = linspace(0.1,1.9,4)';
[XX,YY] = meshgrid(s_vec,s_vec);
rx = XX(:);
ry = YY(:);
clear XX YY s_vec;
rz = 0*rx + 1.05;
GX = [rx, ry, rz;
1, 1, 1.4;
-0.3, 1, 0;
1, -0.3, 0;
2.3, 1, 0;
1, 2.3, 0;
-0.3, -0.3, -0.9;
2.3, -0.3, -0.9;
-0.3, 2.3, -0.9;
2.3, 2.3, -0.9];
Cell_Indices = uint32(ones(size(GX,1),1));
%Cell_Indices = uint32(randi(Mesh.Num_Cell,size(GX,1),1));
Gamma_Neighbors = uint32(Mesh.neighbors);
Gamma_Given_Points = {Cell_Indices, GX, Gamma_Neighbors};
% search!
tic
SEARCH = feval(str2func(mexName),Mesh.Points,uint32(Mesh.ConnectivityList),[],[],Gamma_Given_Points);
toc
RefSEARCHDataFileName = fullfile(Current_Dir,'FEL_Execute_Pt_Search_Surface_In_3D_REF_Data.mat');
% SEARCH_REF = SEARCH;
% save(RefSEARCHDataFileName,'SEARCH_REF');
load(RefSEARCHDataFileName);
status = 0; % init
if ~strcmp(SEARCH.Name,Mesh.Name)
disp('Domain name does not match!');
status = 1;
end
% get closest cell indices
CI = double(SEARCH.DATA{1});
if (min(CI) <= 0)
disp('At least one point was not found in the mesh!');
status = 1;
end
% get corresponding local reference triangle coordinates
Local_Ref_Coord = SEARCH.DATA{2};
N1 = 1 - sum(Local_Ref_Coord,2);
CHK = [N1, Local_Ref_Coord];
MIN_VAL = min(CHK(:));
MAX_VAL = max(CHK(:));
% make sure the coordinates are inside the ref triangle
if ~and(MIN_VAL >= -1e-15, MAX_VAL <= 1 + 1e-15)
disp('Some local points are outside reference triangle!');
status = 1;
end
% check that difference vector is "orthogonal" to the surface
XC = Mesh.referenceToCartesian(CI, Local_Ref_Coord);
Global_X = Gamma_Given_Points{2};
DIFF_VEC = Global_X - XC;
% compute edge vectors
Edges = Mesh.edges;
EV = Mesh.Points(Edges(:,2),:) - Mesh.Points(Edges(:,1),:);
EV11 = normalize_vec(EV(11,:));
EV12 = normalize_vec(EV(12,:));
EV18 = normalize_vec(EV(18,:));
EV19 = normalize_vec(EV(19,:));
EV07 = normalize_vec(EV(7,:));
EV14 = normalize_vec(EV(14,:));
EV17 = normalize_vec(EV(17,:));
EV20 = normalize_vec(EV(20,:));
% compute a few normal vectors
NV03 = normalize_vec(cross(EV11,EV07));
NV04 = normalize_vec(cross(EV14,EV11));
NV05 = normalize_vec(cross(EV07,EV12));
NV08 = normalize_vec(cross(EV17,EV12));
NV10 = normalize_vec(cross(EV14,EV18));
NV11 = normalize_vec(cross(EV20,EV18));
NV13 = normalize_vec(cross(EV19,EV20));
NV14 = normalize_vec(cross(EV17,EV19));
% check "orthogonality"
CHK = zeros(size(Global_X,1),1);
NORM_DIFF_VEC = normalize_vec(DIFF_VEC);
CHK(6) = dot(EV11,NORM_DIFF_VEC(6,:));
CHK(10) = dot(EV12,NORM_DIFF_VEC(10,:));
CHK(7) = dot(EV18,NORM_DIFF_VEC(7,:));
CHK(11) = dot(EV19,NORM_DIFF_VEC(11,:));
CHK(2) = 1 - dot(NV04,NORM_DIFF_VEC(2,:));
CHK(5) = 1 - dot(NV03,NORM_DIFF_VEC(5,:));
CHK(9) = 1 - dot(NV05,NORM_DIFF_VEC(9,:));
CHK(14) = 1 - dot(NV08,NORM_DIFF_VEC(14,:));
CHK(15) = 1 - dot(NV14,NORM_DIFF_VEC(15,:));
CHK(12) = 1 - dot(NV13,NORM_DIFF_VEC(12,:));
CHK(8) = 1 - dot(NV11,NORM_DIFF_VEC(8,:));
CHK(3) = 1 - dot(NV10,NORM_DIFF_VEC(3,:));
ORTHO_ERROR = max(abs(CHK));
if (ORTHO_ERROR > 1e-15)
disp(['Orthogonality Test Failed for Point Searching...']);
status = 1;
end
% plot closest points
figure;
Mesh.Plot;
hold on;
plot3(Global_X(:,1),Global_X(:,2),Global_X(:,3),'k*','MarkerSize',10);
plot3(XC(:,1),XC(:,2),XC(:,3),'r.','MarkerSize',20);
plot3([XC(:,1), Global_X(:,1)]',[XC(:,2), Global_X(:,2)]',[XC(:,3), Global_X(:,3)]','b-');
hold off;
axis([-0.5 2.5 -0.5 2.5 -1 1.5]);
axis equal;
title('Closest Point Search On Triangulation');
% compare to reference data
for ind = 1:length(SEARCH)
ECI = max(abs(SEARCH(ind).DATA{1} - SEARCH_REF(ind).DATA{1}));
ELR = max(abs(SEARCH(ind).DATA{2} - SEARCH_REF(ind).DATA{2}));
if (ECI > 0)
disp(['Test Failed for SEARCH(', num2str(ind), ').DATA{1}...']);
status = 1;
end
if (ELR > 4e-15)
disp(['Test Failed for SEARCH(', num2str(ind), ').DATA{2}...']);
status = 1;
end
end
end
function UNIT_VEC = normalize_vec(VEC)
MAG0 = sqrt(sum(VEC.^2,2));
UNIT_VEC = VEC;
UNIT_VEC(:,1) = VEC(:,1) ./ MAG0;
UNIT_VEC(:,2) = VEC(:,2) ./ MAG0;
UNIT_VEC(:,3) = VEC(:,3) ./ MAG0;
end
|
github
|
eardi/sm-fpca-master
|
FEL_Execute_Pt_Search_Curve_In_2D.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Interpolation/Unit_Test/Point_Searches/TopDim_1_GeoDim_2/FEL_Execute_Pt_Search_Curve_In_2D.m
| 4,244 |
utf_8
|
a5ffbbd3253026813175ddca617964c9
|
function status = FEL_Execute_Pt_Search_Curve_In_2D(mexName)
%FEL_Execute_Pt_Search_Curve_In_2D
%
% test FELICITY Auto-Generated Point Search Code.
% Copyright (c) 07-26-2014, Shawn W. Walker
current_file = mfilename('fullpath');
Current_Dir = fileparts(current_file);
% get test mesh (interval [0, 9])
[Sigma_P1_Vtx, Sigma_Edge] = Standard_Edge_Mesh_Test_Data();
% add y-component
y = 0*Sigma_P1_Vtx(:,1);
Sigma_P1_Vtx = [Sigma_P1_Vtx, y];
Mesh = MeshInterval(Sigma_Edge, Sigma_P1_Vtx, 'Sigma');
% refine
for ind = 1:3
Mesh = Mesh.Refine;
end
% make a sine wave
x = Mesh.Points(:,1);
y = sin(0.2*pi*x);
Mesh = Mesh.Set_Points([x, y]);
% define the global points
% NP = 1000;
% % set some random global points
% rx = 9*rand(NP,1);
% ry = 2*rand(NP,1);
% GX = [rx, ry];
[XX,YY] = meshgrid((0:2:9)',(-1:0.7:1)');
GX = [XX(:), YY(:)];
clear XX YY;
Cell_Indices = uint32(ones(size(GX,1),1));
%Cell_Indices = uint32(randi(Mesh.Num_Cell,size(GX,1),1));
Sigma_Neighbors = uint32(Mesh.neighbors);
Sigma_Given_Points = {Cell_Indices, GX, Sigma_Neighbors};
% search!
tic
SEARCH = feval(str2func(mexName),Mesh.Points,uint32(Mesh.ConnectivityList),[],[],Sigma_Given_Points);
toc
RefSEARCHDataFileName = fullfile(Current_Dir,'FEL_Execute_Pt_Search_Curve_In_2D_REF_Data.mat');
% SEARCH_REF = SEARCH;
% save(RefSEARCHDataFileName,'SEARCH_REF');
load(RefSEARCHDataFileName);
status = 0; % init
if ~strcmp(SEARCH.Name,Mesh.Name)
disp('Domain name does not match!');
status = 1;
end
% get closest cell indices
CI = double(SEARCH.DATA{1});
if (min(CI) <= 0)
disp('At least one point was not found in the mesh!');
status = 1;
end
% get corresponding local reference triangle coordinates
Local_Ref_Coord = SEARCH.DATA{2};
N1 = 1 - sum(Local_Ref_Coord,2);
CHK = [N1, Local_Ref_Coord];
MIN_VAL = min(CHK(:));
MAX_VAL = max(CHK(:));
% make sure the coordinates are inside the ref triangle
if ~and(MIN_VAL >= -1e-15, MAX_VAL <= 1 + 1e-15)
disp('Some local points are outside reference triangle!');
status = 1;
end
% check that difference vector is "orthogonal" to the surface
XC = Mesh.referenceToCartesian(CI, Local_Ref_Coord);
Global_X = Sigma_Given_Points{2};
DIFF_VEC = Global_X - XC;
% look at some of the closest points
PTS_Closest_To_First_End = [1, 2];
ALL_Other_PTS = setdiff((1:1:size(Global_X,1))',PTS_Closest_To_First_End);
% compute edge vectors
Edges = Mesh.edges;
EV = Mesh.Points(Edges(:,2),:) - Mesh.Points(Edges(:,1),:);
UNIT_EV = normalize_vec(EV);
% check "orthogonality"
UNIT_DIFF_VEC = normalize_vec(DIFF_VEC);
CHK_ORTHO = dot(UNIT_EV(CI,:),UNIT_DIFF_VEC,2);
% only the ones in the other set will be ortho
CHK_MAX = CHK_ORTHO(ALL_Other_PTS);
ORTHO_ERROR = max(abs(CHK_MAX));
if (ORTHO_ERROR > 1e-13)
ORTHO_ERROR
disp(['Orthogonality Test Failed for Point Searching...']);
status = 1;
end
% check that the other global points are closest to the ENDS of the parabola
XC_First = XC(PTS_Closest_To_First_End,:);
First_End = [0, 0];
CHK_First = [XC_First(:,1) - First_End(1), XC_First(:,2) - First_End(2)];
CHK_First_MAX = max(abs(CHK_First(:)));
if CHK_First_MAX
disp(['Global Points Not Close To First End Point...']);
status = 1;
end
% plot closest points
figure;
Mesh.Plot;
hold on;
plot(Global_X(:,1),Global_X(:,2),'k*','MarkerSize',10);
plot(XC(:,1),XC(:,2),'r.','MarkerSize',20);
plot([XC(:,1), Global_X(:,1)]',[XC(:,2), Global_X(:,2)]','b-');
hold off;
axis([0 9 -1 1]);
axis equal;
title('Closest Point Search On 2-D Curve Mesh');
% compare to reference data
for ind = 1:length(SEARCH)
ECI = max(abs(SEARCH(ind).DATA{1} - SEARCH_REF(ind).DATA{1}));
ELR = max(abs(SEARCH(ind).DATA{2} - SEARCH_REF(ind).DATA{2}));
if (ECI > 0)
disp(['Test Failed for SEARCH(', num2str(ind), ').DATA{1}...']);
status = 1;
end
if (ELR > 4e-15)
disp(['Test Failed for SEARCH(', num2str(ind), ').DATA{2}...']);
status = 1;
end
end
end
function UNIT_VEC = normalize_vec(VEC)
MAG0 = sqrt(sum(VEC.^2,2));
UNIT_VEC = VEC;
UNIT_VEC(:,1) = VEC(:,1) ./ MAG0;
UNIT_VEC(:,2) = VEC(:,2) ./ MAG0;
end
|
github
|
eardi/sm-fpca-master
|
Elem_DoF_Allocator_class_declaration_3D_tetrahedron.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/DoF_Numbering/@GenDoFNumberingCode/private/Elem_DoF_Allocator_class_declaration_3D_tetrahedron.m
| 21,141 |
utf_8
|
02781f6353844b17dc6b7b270c08d03d
|
function clss = Elem_DoF_Allocator_class_declaration_3D_tetrahedron(obj,Elem)
%Elem_DoF_Allocator_class_declaration_3D_tetrahedron
%
% This stores lines of code for sub-sections of the
% 'Elem_DoF_Allocator.cc' C++ code file.
% Copyright (c) 10-14-2016, Shawn W. Walker
Elem_Nodal_Top = Elem.Nodal_Top;
Elem_Nodal_Var = Elem.Nodal_Var;
%%%%%%%
clss = FELtext('class declaration');
clss = clss.Append_CR(obj.String.Separator);
clss = clss.Append_CR('// data structure containing information on the local element DoF numbering');
clss = clss.Append_CR('typedef struct');
clss = clss.Append_CR('{');
clss = clss.Append_CR(' int V[Num_Vtx_Sets +1][NUM_VTX +1][Max_DoF_Per_Vtx +1]; // nodes associated with each vertex');
clss = clss.Append_CR(' int E[Num_Edge_Sets+1][NUM_EDGE+1][Max_DoF_Per_Edge+1]; // nodes associated with each edge');
clss = clss.Append_CR(' int F[Num_Face_Sets+1][NUM_FACE+1][Max_DoF_Per_Face+1]; // nodes associated with each face');
clss = clss.Append_CR(' int T[Num_Tet_Sets +1][NUM_TET +1][Max_DoF_Per_Tet +1]; // nodes associated with each tetrahedron');
clss = clss.Append_CR('}');
clss = clss.Append_CR('NODAL_TOPOLOGY;');
clss = clss.Append_CR('');
% BEGIN: edge DoF permutations
clss = clss.Append_CR(obj.String.Separator);
clss = clss.Append_CR('// data structure containing *one* permutation map');
clss = clss.Append_CR('typedef struct');
clss = clss.Append_CR('{');
clss = clss.Append_CR(' int map[Max_DoF_Per_Edge+1];');
clss = clss.Append_CR('}');
clss = clss.Append_CR('SINGLE_EDGE_PERM_MAP;');
clss = clss.Append_CR('');
clss = clss.Append_CR(obj.String.Separator);
clss = clss.Append_CR('// data structure for containing permutation maps of local edge DoFs from');
clss = clss.Append_CR('// one local edge to another.');
clss = clss.Append_CR('struct EDGE_DOF_PERMUTATION');
clss = clss.Append_CR('{');
clss = clss.Append_CR(' EDGE_DOF_PERMUTATION () {} // default constructor');
clss = clss.Append_CR('');
clss = clss.Append_CR(' void Setup_Maps ()');
clss = clss.Append_CR(' {');
clss = clss.Append_CR(' // init to all zero');
clss = clss.Append_CR(' for (int di = 0; (di < Num_Edge_Sets); di++)');
clss = clss.Append_CR(' for (int ii = 0; (ii < NUM_EDGE); ii++)');
clss = clss.Append_CR(' for (int si = 0; (si < 2); si++)');
clss = clss.Append_CR(' for (int jj = 0; (jj < NUM_EDGE); jj++)');
clss = clss.Append_CR(' for (int sj = 0; (sj < 2); sj++)');
clss = clss.Append_CR(' for (int kk = 0; (kk <= Max_DoF_Per_Edge); kk++)');
clss = clss.Append_CR(' perm[di][ii][si][jj][sj].map[kk] = 0;');
clss = clss.Append_CR('');
clss = clss.Append_CR(' // define all edge DoF permutation maps');
clss = clss.Append_CR(' // map goes from "current" to "init" local edge');
clss = clss.Append_CR([' ', obj.String.BEGIN_Auto_Gen]);
% map from local edge to tail vertex index
ei_to_tail_vi = [1 1 1 2 3 4];
% map from local edge to head vertex index
ei_to_head_vi = [2 3 4 3 4 2];
if ~isempty(Elem_Nodal_Top.E{1})
Num_Edge_Sets = length(Elem_Nodal_Top.E);
for si = 1:Num_Edge_Sets
Edge_DoF_Set = Elem_Nodal_Top.E{si};
if (size(Edge_DoF_Set,1)~=6)
error('Incorrect number of edges in DoF set!');
end
% within each set, figure out the permutation maps between
% different local edges
% (also account for changes in orientation)
cei_index = [-6 -5 -4 -3 -2 -1 1 2 3 4 5 6];
init_ei_index = cei_index;
% check all combinations
for ii = 1:12 % loop through "current" edges
cei = cei_index(ii);
for jj = 1:12 % loop through "init" edges
init_ei = init_ei_index(jj);
% // DoF set #1, (current) -6 ---> (init) -1
clss = clss.Append_CR([' ', '// DoF set #', num2str(si), ', (current) ', num2str(cei), ' ---> (init) ', num2str(init_ei)]);
% get current and init edge DoFs
cei_DoFs = Edge_DoF_Set(abs(cei),:);
init_ei_DoFs = Edge_DoF_Set(abs(init_ei),:);
% for the "current" edge, get the tail vertex BC coordinate
cei_vi = ei_to_tail_vi(abs(cei));
cei_BCs = get_vtx_barycentric_coordinate_on_edge(cei_DoFs,Elem_Nodal_Var,cei_vi);
% for the "init" edge, get the tail or head vertex BC coordinate
% (depending on whether the edge orientation is different)
if (cei*init_ei < 0) % change in orientation
init_ei_vi = ei_to_head_vi(abs(init_ei));
else
init_ei_vi = ei_to_tail_vi(abs(init_ei));
end
init_ei_BCs = get_vtx_barycentric_coordinate_on_edge(init_ei_DoFs,Elem_Nodal_Var,init_ei_vi);
% Note: these lists of barycentric coordinates are in the
% order of cei_DoFs/init_ei_DoFs
% getting permutation of DoFs from comparing BC lists
DoF_perm = get_DoF_permutation_on_edge(cei_BCs,init_ei_BCs);
for kk = 1:length(DoF_perm)
if cei > 0
sign_cei = 1;
else
sign_cei = 0;
end
if init_ei > 0
sign_init_ei = 1;
else
sign_init_ei = 0;
end
clss = clss.Append_CR([' ', 'perm[', num2str(si-1), '][',...
num2str(abs(cei)-1), '][', num2str(sign_cei), '][',...
num2str(abs(init_ei)-1), '][', num2str(sign_init_ei), '].map[',...
num2str(kk), '] = ', num2str(DoF_perm(kk)), ';']);
end
clss = clss.Append_CR('');
end
end
end
else
Num_Edge_Sets = 0;
end
clss = clss.Append_CR([' ', obj.String.END_Auto_Gen]);
clss = clss.Append_CR(' }');
clss = clss.Append_CR('');
clss = clss.Append_CR(' inline const int* Get_Map (const int& dof_set, const int& new_edge, const int& init_edge) const');
clss = clss.Append_CR(' {');
clss = clss.Append_CR(' // error check');
clss = clss.Append_CR(' if ((new_edge==0) || (new_edge < -6) || (new_edge > 6))');
clss = clss.Append_CR(' {');
clss = clss.Append_CR(' mexPrintf("new_edge must be = +/- 1,2,3,4,5,6.\\n");');
clss = clss.Append_CR(' mexErrMsgTxt("Invalid local edge index!\\n");');
clss = clss.Append_CR(' }');
clss = clss.Append_CR(' if ((init_edge==0) || (init_edge < -6) || (init_edge > 6))');
clss = clss.Append_CR(' {');
clss = clss.Append_CR(' mexPrintf("init_edge must be = +/- 1,2,3,4,5,6.\\n");');
clss = clss.Append_CR(' mexErrMsgTxt("Invalid local edge index!\\n");');
clss = clss.Append_CR(' }');
clss = clss.Append_CR(' if ((dof_set < 1) || (dof_set > Num_Edge_Sets))');
clss = clss.Append_CR(' {');
clss = clss.Append_CR(' mexPrintf("dof_set must be >= 1 and <= %%d.\\n",Num_Edge_Sets);');
clss = clss.Append_CR(' mexErrMsgTxt("Invalid dof_set index!\\n");');
clss = clss.Append_CR(' }');
clss = clss.Append_CR('');
clss = clss.Append_CR(' // massage input');
clss = clss.Append_CR(' const int ne = abs_index( new_edge) - 1; // C-style indexing');
clss = clss.Append_CR(' const int ie = abs_index(init_edge) - 1; // C-style indexing');
clss = clss.Append_CR(' int sign_ne = 1; // init to positive');
clss = clss.Append_CR(' int sign_ie = 1; // init to positive');
clss = clss.Append_CR(' if ( new_edge < 0) sign_ne = 0; // set to negative sign');
clss = clss.Append_CR(' if (init_edge < 0) sign_ie = 0; // set to negative sign');
clss = clss.Append_CR('');
clss = clss.Append_CR(' return perm[dof_set-1][ne][sign_ne][ie][sign_ie].map;');
clss = clss.Append_CR(' }');
clss = clss.Append_CR('');
clss = clss.Append_CR('private:');
clss = clss.Append_CR(' // contains all of the permutation maps');
clss = clss.Append_CR(' // input: [dof_set][new_edge_index][sign of new_edge][init_edge_index][sign of init_edge]');
if (Num_Edge_Sets > 0)
clss = clss.Append_CR(' SINGLE_EDGE_PERM_MAP perm[Num_Edge_Sets][NUM_EDGE][2][NUM_EDGE][2];');
else
clss = clss.Append_CR(' // NOTE: this is not used b/c there are no edge sets!');
clss = clss.Append_CR(' SINGLE_EDGE_PERM_MAP perm[1][NUM_EDGE][2][NUM_EDGE][2];');
end
clss = clss.Append_CR('};');
clss = clss.Append_CR('');
% END: edge DoF permutations
% BEGIN: face DoF permutations
clss = clss.Append_CR(obj.String.Separator);
clss = clss.Append_CR('// data structure containing *one* face-DoF permutation map');
clss = clss.Append_CR('typedef struct');
clss = clss.Append_CR('{');
clss = clss.Append_CR(' int map[Max_DoF_Per_Face+1];');
clss = clss.Append_CR('}');
clss = clss.Append_CR('SINGLE_FACE_PERM_MAP;');
clss = clss.Append_CR('');
clss = clss.Append_CR(obj.String.Separator);
clss = clss.Append_CR('// data structure for containing permutation maps of local face DoFs from');
clss = clss.Append_CR('// one local face to another.');
clss = clss.Append_CR('struct FACE_DOF_PERMUTATION');
clss = clss.Append_CR('{');
clss = clss.Append_CR(' FACE_DOF_PERMUTATION () {} // default constructor');
clss = clss.Append_CR('');
clss = clss.Append_CR(' void Setup_Maps ()');
clss = clss.Append_CR(' {');
clss = clss.Append_CR(' // init to all zero');
clss = clss.Append_CR(' for (int di = 0; (di < Num_Face_Sets); di++)');
clss = clss.Append_CR(' for (int ii = 0; (ii < NUM_FACE); ii++)');
clss = clss.Append_CR(' for (int si = 0; (si < 6); si++)');
clss = clss.Append_CR(' for (int jj = 0; (jj < NUM_FACE); jj++)');
clss = clss.Append_CR(' for (int sj = 0; (sj < 6); sj++)');
clss = clss.Append_CR(' for (int kk = 0; (kk <= Max_DoF_Per_Face); kk++)');
clss = clss.Append_CR(' perm[di][ii][si][jj][sj].map[kk] = 0;');
clss = clss.Append_CR('');
clss = clss.Append_CR(' // define all face DoF permutation maps');
clss = clss.Append_CR(' // map goes from "current" to "init" local face');
clss = clss.Append_CR([' ', obj.String.BEGIN_Auto_Gen]);
% map from local face index to set of three vertex indices
fi_to_vtx = [2 3 4;
1 4 3;
1 2 4;
1 3 2];
%
% define the 6 permutations
face_perm = [1 2 3; % 1
3 1 2; % 2
2 3 1; % 3
3 2 1; % 4
2 1 3; % 5
1 3 2]; % 6
%
if ~isempty(Elem_Nodal_Top.F{1})
Num_Face_Sets = length(Elem_Nodal_Top.F);
for si = 1:Num_Face_Sets
Face_DoF_Set = Elem_Nodal_Top.F{si};
if (size(Face_DoF_Set,1)~=4)
error('Incorrect number of faces in DoF set!');
end
% within each set, figure out the permutation maps between
% different local faces
% (check all combinations)
% loop through "current" faces
for cfi = 1:4
for perm_cfi_index = 1:6 % all permutations
perm_cfi = face_perm(perm_cfi_index,:);
% loop through "init" faces
for init_fi = 1:4
for perm_init_index = 1:6 % all permutations
perm_init = face_perm(perm_init_index,:);
%init_ei = init_ei_index(jj);
% // DoF set #1, (current: face, perm) 2, 4 ---> (init: face, perm) 1, 2
clss = clss.Append_CR([' ', '// DoF set #', num2str(si), ', (current: face, perm) ',...
num2str(cfi), ', [', num2str(perm_cfi), ']',...
' ---> (init: face, perm) ',...
num2str(init_fi), ', [', num2str(perm_init), ']']);
% get current and init face DoFs
cfi_DoFs = Face_DoF_Set(cfi,:);
init_fi_DoFs = Face_DoF_Set(init_fi,:);
% for the "current" face, get the (permuted) BC coordinates
current_face_vertices = fi_to_vtx(cfi,:);
cfi_BCs = get_vtx_barycentric_coordinates_on_face(cfi_DoFs,Elem_Nodal_Var,current_face_vertices(1,perm_cfi));
% for the "init" face, get the (permuted) BC coordinates
init_face_vertices = fi_to_vtx(init_fi,:);
init_fi_BCs = get_vtx_barycentric_coordinates_on_face(init_fi_DoFs,Elem_Nodal_Var,init_face_vertices(1,perm_init));
% get permutation of DoFs by comparing BC coordinates
DoF_perm = get_DoF_permutation_on_face(cfi_BCs,init_fi_BCs);
for kk = 1:length(DoF_perm)
clss = clss.Append_CR([' ', 'perm[', num2str(si-1), '][',...
num2str(cfi-1), '][', num2str(perm_cfi_index-1), '][',...
num2str(init_fi-1), '][', num2str(perm_init_index-1), '].map[',...
num2str(kk), '] = ', num2str(DoF_perm(kk)), ';']);
end
clss = clss.Append_CR('');
end
end
end
end
end
else
Num_Face_Sets = 0;
end
clss = clss.Append_CR([' ', obj.String.END_Auto_Gen]);
clss = clss.Append_CR(' }');
clss = clss.Append_CR('');
clss = clss.Append_CR(' inline const int* Get_Map (const int& dof_set, const int& new_face, const int& perm_new,');
clss = clss.Append_CR(' const int& init_face, const int& perm_init) const');
clss = clss.Append_CR(' {');
clss = clss.Append_CR(' // error check');
clss = clss.Append_CR(' if ((new_face < 1) || (new_face > 4))');
clss = clss.Append_CR(' {');
clss = clss.Append_CR(' mexPrintf("new_face must be = 1,2,3,4.\\n");');
clss = clss.Append_CR(' mexErrMsgTxt("Invalid local face index!\\n");');
clss = clss.Append_CR(' }');
clss = clss.Append_CR(' if ((perm_new < 1) || (perm_new > 6))');
clss = clss.Append_CR(' {');
clss = clss.Append_CR(' mexPrintf("perm_new must be = 1,2,3,4,5,6.\\n");');
clss = clss.Append_CR(' mexErrMsgTxt("Invalid permutation index!\\n");');
clss = clss.Append_CR(' }');
clss = clss.Append_CR(' if ((init_face < 1) || (init_face > 4))');
clss = clss.Append_CR(' {');
clss = clss.Append_CR(' mexPrintf("init_face must be = 1,2,3,4.\\n");');
clss = clss.Append_CR(' mexErrMsgTxt("Invalid local face index!\\n");');
clss = clss.Append_CR(' }');
clss = clss.Append_CR(' if ((perm_init < 1) || (perm_init > 6))');
clss = clss.Append_CR(' {');
clss = clss.Append_CR(' mexPrintf("perm_init must be = 1,2,3,4,5,6.\\n");');
clss = clss.Append_CR(' mexErrMsgTxt("Invalid permutation index!\\n");');
clss = clss.Append_CR(' }');
clss = clss.Append_CR(' if ((dof_set < 1) || (dof_set > Num_Face_Sets))');
clss = clss.Append_CR(' {');
clss = clss.Append_CR(' mexPrintf("dof_set must be >= 1 and <= %%d.\\n",Num_Face_Sets);');
clss = clss.Append_CR(' mexErrMsgTxt("Invalid dof_set index!\\n");');
clss = clss.Append_CR(' }');
clss = clss.Append_CR('');
clss = clss.Append_CR(' return perm[dof_set-1][new_face-1][perm_new-1][init_face-1][perm_init-1].map;');
clss = clss.Append_CR(' }');
clss = clss.Append_CR('');
clss = clss.Append_CR('private:');
clss = clss.Append_CR(' // contains all of the permutation maps');
clss = clss.Append_CR(' // input: [dof_set][new_face_index][perm of new_face][init_face_index][perm of init_face]');
if (Num_Face_Sets > 0)
clss = clss.Append_CR(' SINGLE_FACE_PERM_MAP perm[Num_Face_Sets][NUM_FACE][6][NUM_FACE][6];');
else
clss = clss.Append_CR(' // NOTE: this is not used b/c there are no face sets!');
clss = clss.Append_CR(' SINGLE_FACE_PERM_MAP perm[1][NUM_FACE][6][NUM_FACE][6];');
end
clss = clss.Append_CR('};');
clss = clss.Append_CR('');
% END: face DoF permutations
clss = clss.Append_CR(obj.String.Separator);
clss = clss.Append_CR('class EDA');
clss = clss.Append_CR('{');
clss = clss.Append_CR('public:');
clss = clss.Append_CR(' char* Name; // name of finite element space');
clss = clss.Append_CR(' int Dim; // intrinsic dimension');
clss = clss.Append_CR(' char* Domain; // type of domain: "interval", "triangle", "tetrahedron"');
clss = clss.Append_CR('');
clss = clss.Append_CR(' NODAL_TOPOLOGY Node; // Nodal DoF arrangment');
clss = clss.Append_CR(' EDGE_DOF_PERMUTATION Edge_DoF_Perm; // permutation maps for local edge DoFs:');
clss = clss.Append_CR(' // this is for allocating DoFs on edges');
clss = clss.Append_CR(' // consistently between elements.');
clss = clss.Append_CR(' FACE_DOF_PERMUTATION Face_DoF_Perm; // permutation maps for local face DoFs:');
clss = clss.Append_CR(' // this is for allocating DoFs on faces');
clss = clss.Append_CR(' // consistently between elements.');
clss = clss.Append_CR('');
clss = clss.Append_CR(' EDA (); // constructor');
clss = clss.Append_CR(' ~EDA (); // DE-structor');
clss = clss.Append_CR(' mxArray* Init_DoF_Map(int);');
clss = clss.Append_CR(' void Fill_DoF_Map (TETRAHEDRON_DATA*);');
clss = clss.Append_CR(' int Assign_Vtx_DoF (TETRAHEDRON_DATA*, const int);');
clss = clss.Append_CR(' int Assign_Edge_DoF(TETRAHEDRON_DATA*, const int);');
clss = clss.Append_CR(' int Assign_Face_DoF(TETRAHEDRON_DATA*, const int);');
clss = clss.Append_CR(' int Assign_Tet_DoF (TETRAHEDRON_DATA*, const int);');
clss = clss.Append_CR(' void Error_Check_DoF_Map(const int&);');
clss = clss.Append_CR('');
clss = clss.Append_CR('private:');
clss = clss.Append_CR(' int* cell_dof[Total_DoF_Per_Cell+1];');
clss = clss.Append_CR('};');
clss = clss.Append_CR('');
end
function BCs = get_vtx_barycentric_coordinate_on_edge(DoFs,Nodal_Var,vi)
% get the vertex BC coordinate for each DoF
Num_DoFs = length(DoFs);
BCs = zeros(Num_DoFs,1);
for di = 1:Num_DoFs
Nodal_Var_Data = Nodal_Var(DoFs(di)).Data;
BC_all = Nodal_Var_Data{1};
BCs(di,1) = BC_all(vi);
end
end
function DoF_perm = get_DoF_permutation_on_edge(cei_BCs,init_ei_BCs)
Num_DoF = length(cei_BCs);
DoF_perm = zeros(Num_DoF,1);
% compare the BC coordinates of each DoF in cei and init_ei
for cc_BC_index = 1:Num_DoF
cc_BC_value = cei_BCs(cc_BC_index);
for ii_BC_index = 1:Num_DoF
ii_BC_value = init_ei_BCs(ii_BC_index);
if ( abs(cc_BC_value - ii_BC_value) < 1e-15 )
DoF_perm(cc_BC_index) = ii_BC_index; % map "current" to "init"
break;
end
end
end
if min(DoF_perm)==0
error('At least one DoF was not matched up!');
end
if (length(unique(DoF_perm))~=Num_DoF)
error('Some DoFs got duplicated!');
end
end
function BCs = get_vtx_barycentric_coordinates_on_face(DoFs,Nodal_Var,face_vertices)
% get the vertex BC coordinates for each DoF (in the face)
Num_DoFs = length(DoFs);
BCs = zeros(Num_DoFs,3);
for di = 1:Num_DoFs
Nodal_Var_Data = Nodal_Var(DoFs(di)).Data;
BC_all = Nodal_Var_Data{1};
BCs(di,:) = BC_all(1,face_vertices);
end
end
function DoF_perm = get_DoF_permutation_on_face(cfi_BCs,init_fi_BCs)
Num_DoF = size(cfi_BCs,1);
DoF_perm = zeros(Num_DoF,1);
% compare the BC coordinates of each DoF in cfi and init_fi
for cc_BC_index = 1:Num_DoF
cc_BC_value = cfi_BCs(cc_BC_index,:);
for ii_BC_index = 1:Num_DoF
ii_BC_value = init_fi_BCs(ii_BC_index,:);
% compute norm of difference
Diff_1 = max(abs(cc_BC_value - ii_BC_value));
if ( Diff_1 < 1e-15 )
DoF_perm(cc_BC_index) = ii_BC_index; % map "current" to "init"
break;
end
end
end
if min(DoF_perm)==0
error('At least one DoF was not matched up!');
end
if (length(unique(DoF_perm))~=Num_DoF)
error('Some DoFs got duplicated!');
end
end
|
github
|
eardi/sm-fpca-master
|
Elem_DoF_Allocator_class_declaration_2D_triangle.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/DoF_Numbering/@GenDoFNumberingCode/private/Elem_DoF_Allocator_class_declaration_2D_triangle.m
| 11,622 |
utf_8
|
f04f8556c207417053c451c50d554c4a
|
function clss = Elem_DoF_Allocator_class_declaration_2D_triangle(obj,Elem)
%Elem_DoF_Allocator_class_declaration_2D_triangle
%
% This stores lines of code for sub-sections of the
% 'Elem_DoF_Allocator.cc' C++ code file.
% Copyright (c) 10-14-2016, Shawn W. Walker
Elem_Nodal_Top = Elem.Nodal_Top;
Elem_Nodal_Var = Elem.Nodal_Var;
%%%%%%%
clss = FELtext('class declaration');
clss = clss.Append_CR(obj.String.Separator);
clss = clss.Append_CR('// data structure containing information on the local element DoF numbering');
clss = clss.Append_CR('typedef struct');
clss = clss.Append_CR('{');
clss = clss.Append_CR(' int V[Num_Vtx_Sets +1][NUM_VTX +1][Max_DoF_Per_Vtx +1]; // nodes associated with each vertex');
clss = clss.Append_CR(' int E[Num_Edge_Sets+1][NUM_EDGE+1][Max_DoF_Per_Edge+1]; // nodes associated with each edge');
clss = clss.Append_CR(' int F[Num_Face_Sets+1][NUM_FACE+1][Max_DoF_Per_Face+1]; // nodes associated with each face');
clss = clss.Append_CR(' int T[Num_Tet_Sets +1][NUM_TET +1][Max_DoF_Per_Tet +1]; // nodes associated with each tetrahedron');
clss = clss.Append_CR('}');
clss = clss.Append_CR('NODAL_TOPOLOGY;');
clss = clss.Append_CR('');
clss = clss.Append_CR(obj.String.Separator);
clss = clss.Append_CR('// data structure containing *one* permutation map');
clss = clss.Append_CR('typedef struct');
clss = clss.Append_CR('{');
clss = clss.Append_CR(' int map[Max_DoF_Per_Edge+1];');
clss = clss.Append_CR('}');
clss = clss.Append_CR('SINGLE_EDGE_PERM_MAP;');
clss = clss.Append_CR('');
clss = clss.Append_CR(obj.String.Separator);
clss = clss.Append_CR('// data structure for containing permutation maps of local edge DoFs from');
clss = clss.Append_CR('// one local edge to another.');
clss = clss.Append_CR('struct EDGE_DOF_PERMUTATION');
clss = clss.Append_CR('{');
clss = clss.Append_CR(' EDGE_DOF_PERMUTATION () {} // default constructor');
clss = clss.Append_CR('');
clss = clss.Append_CR(' void Setup_Maps ()');
clss = clss.Append_CR(' {');
clss = clss.Append_CR(' // init to all zero');
clss = clss.Append_CR(' for (int di = 0; (di < Num_Edge_Sets); di++)');
clss = clss.Append_CR(' for (int ii = 0; (ii < NUM_EDGE); ii++)');
clss = clss.Append_CR(' for (int si = 0; (si < 2); si++)');
clss = clss.Append_CR(' for (int jj = 0; (jj < NUM_EDGE); jj++)');
clss = clss.Append_CR(' for (int sj = 0; (sj < 2); sj++)');
clss = clss.Append_CR(' for (int kk = 0; (kk <= Max_DoF_Per_Edge); kk++)');
clss = clss.Append_CR(' perm[di][ii][si][jj][sj].map[kk] = 0;');
clss = clss.Append_CR('');
clss = clss.Append_CR(' // define all edge DoF permutation maps');
clss = clss.Append_CR(' // map goes from "current" to "init" local edge');
clss = clss.Append_CR([' ', obj.String.BEGIN_Auto_Gen]);
% map from local edge to tail vertex index
ei_to_tail_vi = [2 3 1];
% map from local edge to head vertex index
ei_to_head_vi = [3 1 2];
if ~isempty(Elem_Nodal_Top.E{1})
Num_Sets = length(Elem_Nodal_Top.E);
for si = 1:Num_Sets
Edge_DoF_Set = Elem_Nodal_Top.E{si};
if (size(Edge_DoF_Set,1)~=3)
error('Incorrect number of edges in DoF set!');
end
% within each set, figure out the permutation maps between
% different local edges
% (also account for changes in orientation)
cei_index = [-3 -2 -1 1 2 3];
init_ei_index = cei_index;
% check all combinations
for ii = 1:6 % loop through "current" edges
cei = cei_index(ii);
for jj = 1:6 % loop through "init" edges
init_ei = init_ei_index(jj);
% // DoF set #1, (current) -3 ---> (init) -1
clss = clss.Append_CR([' ', '// DoF set #', num2str(si), ', (current) ', num2str(cei), ' ---> (init) ', num2str(init_ei)]);
% get current and init edge DoFs
cei_DoFs = Edge_DoF_Set(abs(cei),:);
init_ei_DoFs = Edge_DoF_Set(abs(init_ei),:);
% for the "current" edge, get the tail vertex BC coordinate
cei_vi = ei_to_tail_vi(abs(cei));
cei_BCs = get_vtx_barycentric_coordinate(cei_DoFs,Elem_Nodal_Var,cei_vi);
% for the "init" edge, get the tail or head vertex BC coordinate
% (depending on whether the edge orientation is different)
if (cei*init_ei < 0) % change in orientation
init_ei_vi = ei_to_head_vi(abs(init_ei));
else
init_ei_vi = ei_to_tail_vi(abs(init_ei));
end
init_ei_BCs = get_vtx_barycentric_coordinate(init_ei_DoFs,Elem_Nodal_Var,init_ei_vi);
% Note: these lists of barycentric coordinates are in the
% order of cei_DoFs/init_ei_DoFs
% getting permutation of DoFs from comparing BC lists
DoF_perm = get_DoF_permutation(cei_BCs,init_ei_BCs);
for kk = 1:length(DoF_perm)
if cei > 0
sign_cei = 1;
else
sign_cei = 0;
end
if init_ei > 0
sign_init_ei = 1;
else
sign_init_ei = 0;
end
clss = clss.Append_CR([' ', 'perm[', num2str(si-1), '][',...
num2str(abs(cei)-1), '][', num2str(sign_cei), '][',...
num2str(abs(init_ei)-1), '][', num2str(sign_init_ei), '].map[',...
num2str(kk), '] = ', num2str(DoF_perm(kk)), ';']);
end
clss = clss.Append_CR('');
end
end
end
else
Num_Sets = 0;
end
clss = clss.Append_CR([' ', obj.String.END_Auto_Gen]);
clss = clss.Append_CR(' }');
clss = clss.Append_CR('');
clss = clss.Append_CR(' inline const int* Get_Map (const int& dof_set, const int& new_edge, const int& init_edge) const');
clss = clss.Append_CR(' {');
clss = clss.Append_CR(' // error check');
clss = clss.Append_CR(' if ((new_edge==0) || (new_edge < -3) || (new_edge > 3))');
clss = clss.Append_CR(' {');
clss = clss.Append_CR(' mexPrintf("new_edge must be = +/- 1,2,3.\\n");');
clss = clss.Append_CR(' mexErrMsgTxt("Invalid local edge index!\\n");');
clss = clss.Append_CR(' }');
clss = clss.Append_CR(' if ((init_edge==0) || (init_edge < -3) || (init_edge > 3))');
clss = clss.Append_CR(' {');
clss = clss.Append_CR(' mexPrintf("init_edge must be = +/- 1,2,3.\\n");');
clss = clss.Append_CR(' mexErrMsgTxt("Invalid local edge index!\\n");');
clss = clss.Append_CR(' }');
clss = clss.Append_CR(' if ((dof_set < 1) || (dof_set > Num_Edge_Sets))');
clss = clss.Append_CR(' {');
clss = clss.Append_CR(' mexPrintf("dof_set must be >= 1 and <= %%d.\\n",Num_Edge_Sets);');
clss = clss.Append_CR(' mexErrMsgTxt("Invalid dof_set index!\\n");');
clss = clss.Append_CR(' }');
clss = clss.Append_CR('');
clss = clss.Append_CR(' // massage input');
clss = clss.Append_CR(' const int ne = abs_index( new_edge) - 1; // C-style indexing');
clss = clss.Append_CR(' const int ie = abs_index(init_edge) - 1; // C-style indexing');
clss = clss.Append_CR(' int sign_ne = 1; // init to positive');
clss = clss.Append_CR(' int sign_ie = 1; // init to positive');
clss = clss.Append_CR(' if ( new_edge < 0) sign_ne = 0; // set to negative sign');
clss = clss.Append_CR(' if (init_edge < 0) sign_ie = 0; // set to negative sign');
clss = clss.Append_CR('');
clss = clss.Append_CR(' return perm[dof_set-1][ne][sign_ne][ie][sign_ie].map;');
clss = clss.Append_CR(' }');
clss = clss.Append_CR('');
clss = clss.Append_CR('private:');
clss = clss.Append_CR(' // contains all of the permutation maps');
clss = clss.Append_CR(' // input: [dof_set][new_edge_index][sign of new_edge][init_edge_index][sign of init_edge]');
if (Num_Sets > 0)
clss = clss.Append_CR(' SINGLE_EDGE_PERM_MAP perm[Num_Edge_Sets][NUM_EDGE][2][NUM_EDGE][2];');
else
clss = clss.Append_CR(' // NOTE: this is not used b/c there are no edge sets!');
clss = clss.Append_CR(' SINGLE_EDGE_PERM_MAP perm[1][NUM_EDGE][2][NUM_EDGE][2];');
end
clss = clss.Append_CR('};');
clss = clss.Append_CR('');
clss = clss.Append_CR(obj.String.Separator);
clss = clss.Append_CR('class EDA');
clss = clss.Append_CR('{');
clss = clss.Append_CR('public:');
clss = clss.Append_CR(' char* Name; // name of finite element space');
clss = clss.Append_CR(' int Dim; // intrinsic dimension');
clss = clss.Append_CR(' char* Domain; // type of domain: "interval", "triangle", "tetrahedron"');
clss = clss.Append_CR('');
clss = clss.Append_CR(' NODAL_TOPOLOGY Node; // Nodal DoF arrangment');
clss = clss.Append_CR(' EDGE_DOF_PERMUTATION Edge_DoF_Perm; // permutation maps for local edge DoFs:');
clss = clss.Append_CR(' // this is for allocating DoFs on edges');
clss = clss.Append_CR(' // consistently between elements.');
clss = clss.Append_CR('');
clss = clss.Append_CR(' EDA (); // constructor');
clss = clss.Append_CR(' ~EDA (); // DE-structor');
clss = clss.Append_CR(' mxArray* Init_DoF_Map(int);');
clss = clss.Append_CR(' void Fill_DoF_Map (TRIANGLE_EDGE_SEARCH*);');
clss = clss.Append_CR(' int Assign_Vtx_DoF (TRIANGLE_EDGE_SEARCH*, const int);');
clss = clss.Append_CR(' int Assign_Edge_DoF(TRIANGLE_EDGE_SEARCH*, const int);');
clss = clss.Append_CR(' int Assign_Face_DoF(TRIANGLE_EDGE_SEARCH*, const int);');
clss = clss.Append_CR(' int Assign_Tet_DoF (TRIANGLE_EDGE_SEARCH*, const int);');
clss = clss.Append_CR(' void Error_Check_DoF_Map(const int&);');
clss = clss.Append_CR('');
clss = clss.Append_CR('private:');
clss = clss.Append_CR(' int* cell_dof[Total_DoF_Per_Cell+1];');
clss = clss.Append_CR('};');
clss = clss.Append_CR('');
end
function BCs = get_vtx_barycentric_coordinate(DoFs,Nodal_Var,vi)
% get the vertex BC coordinate for each DoF
Num_DoFs = length(DoFs);
BCs = zeros(Num_DoFs,1);
for di = 1:Num_DoFs
Nodal_Var_Data = Nodal_Var(DoFs(di)).Data;
BC_all = Nodal_Var_Data{1};
BCs(di,1) = BC_all(vi);
end
end
function DoF_perm = get_DoF_permutation(cei_BCs,init_ei_BCs)
Num_DoF = length(cei_BCs);
DoF_perm = zeros(Num_DoF,1);
% compare the BC coordinates of each DoF in cei and init_ei
for cc_BC_index = 1:Num_DoF
cc_BC_value = cei_BCs(cc_BC_index);
for ii_BC_index = 1:Num_DoF
ii_BC_value = init_ei_BCs(ii_BC_index);
if ( abs(cc_BC_value - ii_BC_value) < 1e-15 )
DoF_perm(cc_BC_index) = ii_BC_index; % map "current" to "init"
break;
end
end
end
if min(DoF_perm)==0
error('At least one DoF was not matched up!');
end
if (length(unique(DoF_perm))~=Num_DoF)
error('Some DoFs got duplicated!');
end
end
|
github
|
eardi/sm-fpca-master
|
Get_Local_Geom_Functions.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Super_Classes/Level_3/@FELExpression/Get_Local_Geom_Functions.m
| 1,139 |
utf_8
|
1af5f161aa08dcfe6c92bba382265b52
|
function GEOM = Get_Local_Geom_Functions(obj,Spaces,Integration_Index)
%Get_Local_Geom_Functions
%
% This returns a struct containing info about the local geometric functions needed for
% the current domain of expression.
% note: geometric functions are ``fresh'' everytime (all options off)
% Copyright (c) 06-12-2014, Shawn W. Walker
% the Domain of Expression (DoE) geometric information
% SWW: bad notation here!
GEOM.DoI_Geom = Spaces.Integration(Integration_Index).DoI_Geom;
% get other geometric functions
GeomFuncs = Spaces.Integration(Integration_Index).GeomFunc;
Num_Funcs = length(GeomFuncs);
Geom_Names = GeomFuncs.keys;
if (Num_Funcs > 0)
% geometric function
GEOM.GF = output_struct(Integration_Index,GeomFuncs(Geom_Names{1}));
for ind = 2:Num_Funcs
GEOM.GF(ind) = output_struct(Integration_Index,GeomFuncs(Geom_Names{ind}));
end
else
GEOM.GF = [];
end
end
function GF = output_struct(Integration_Index,GeomFunc)
% geometric function
GF.func = GeomFunc;
GF.Integration_Index = Integration_Index;
GF.func = GF.func.Reset_Options;
end
|
github
|
eardi/sm-fpca-master
|
Get_Local_Coef_Functions.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Super_Classes/Level_3/@FELExpression/Get_Local_Coef_Functions.m
| 1,046 |
utf_8
|
85132f9644bdd53e1f358dde17f4e4c6
|
function CF = Get_Local_Coef_Functions(obj,Spaces,Integration_Index)
%Get_Local_Coef_Functions
%
% This returns a struct containing info about the local coefficient functions.
% note: coef functions are ``fresh'' everytime (all options off)
% Copyright (c) 03-24-2017, Shawn W. Walker
Coefs = Spaces.Integration(Integration_Index).CoefFunc;
Num_Funcs = length(Coefs);
Coef_Names = Coefs.keys;
if (Num_Funcs > 0)
% coefficient function
CF = output_struct(Spaces,Integration_Index,Coefs(Coef_Names{1}));
for ind = 2:Num_Funcs
CF(ind) = output_struct(Spaces,Integration_Index,Coefs(Coef_Names{ind}));
end
else
CF = [];
end
end
function CF = output_struct(Spaces,Integration_Index,CoefFunc)
% coefficient function
CF.str = CoefFunc.Func_Name;
CF.func = CoefFunc;
CF.Integration_Index = Integration_Index;
% store the vector dimension of FE space
f_Space = Spaces.Space(CF.func.Space_Name);
CF.Space_Num_Comp = f_Space.Num_Comp;
CF.func = CF.func.Reset_Options;
end
|
github
|
eardi/sm-fpca-master
|
Robust_Var_Name_Replacements.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Super_Classes/Level_3/@FELExpression/Robust_Var_Name_Replacements.m
| 1,309 |
utf_8
|
e66b02287da17b4285dee40bfc158e88
|
function [New_Sym_Exp, New_Var_Names] = Robust_Var_Name_Replacements(obj,Sym_Exp,Var_Names)
%Robust_Var_Name_Replacements
%
% This replaces all the variable names in the symbolic expression ``Sym_Exp''
% with new variable names that have DISTINCT names. This is done to ensure
% that no name is a subset of another one, which can screw up the text
% replacements. The list of variable names is given in ``Var_Names''.
%
% Note: these replacements are done symbolically, so it won't get confused!
% Copyright (c) 04-10-2012, Shawn W. Walker
% init
New_Sym_Exp = Sym_Exp;
New_Var_Names = Var_Names;
% create new distinct variable names
Num_Vars = length(Var_Names(:));
for ind = 1:Num_Vars
Var_Name_str = Get_Indexed_Var_Name(ind);
New_Var_Names(ind) = sym(Var_Name_str);
end
subs_H = FEL_subs_handle();
for ind = 1:Num_Vars
New_Sym_Exp = subs_H(New_Sym_Exp,Var_Names(ind),New_Var_Names(ind));
end
end
function Var_Name_str = Get_Indexed_Var_Name(index)
if index > 100000
error('This index is too big!');
end
index_str = num2str(index);
len_index_str = length(index_str);
padded_index_str = '000000';
padded_index_str(end - len_index_str + 1:end) = index_str;
Var_Name_str = ['FELICITYVARNAMEABC', padded_index_str, 'XYZ'];
end
|
github
|
eardi/sm-fpca-master
|
Need_Orientation.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Super_Classes/Ghost_Writers/@Generic_GenFELCode/Need_Orientation.m
| 726 |
utf_8
|
daa2cb3eec11cb1a7f95010cf58cc961
|
function TF = Need_Orientation(obj,FS)
%Need_Orientation
%
% This indicates if mesh orientation data is needed.
% Copyright (c) 06-25-2012, Shawn W. Walker
TF = false;
for ind = 1:length(FS.Integration)
Opt = FS.Integration(ind).DoI_Geom.Opt;
TF = orientation_present(Opt);
if ~TF
BF_Set = FS.Integration(ind).BasisFunc.values;
for bi = 1:length(BF_Set)
Opt = BF_Set{bi}.GeomFunc.Opt;
TF = orientation_present(Opt);
end
end
if TF
break;
end
end
end
function TF = orientation_present(Opt)
TF = false;
if isfield(Opt,'Orientation')
if Opt.Orientation
TF = true;
end
end
end
|
github
|
eardi/sm-fpca-master
|
Gen_Misc_Matrix_Assembler.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Super_Classes/Ghost_Writers/@Generic_GenFELCode/Gen_Misc_Matrix_Assembler.m
| 1,499 |
utf_8
|
ac4c6b551d264710143b6389a0775e37
|
function Gen_Misc_Matrix_Assembler(obj,fid)
%Gen_Misc_Matrix_Assembler
%
% This generates a section of Misc_Stuff.h: the core matrix assembly code.
% fid = an (open) file ID to "Misc_Stuff.h".
% Copyright (c) 06-13-2014, Shawn W. Walker
% copy some standard files over
FC = FELCodeHdr();
% assembler
obj.Make_SubDir(obj.Sub_Dir.Assembler);
Assem_Dir = fullfile(obj.Output_Dir, obj.Sub_Dir.Assembler);
Matrix_Assembler_Files = FC.Copy_Matrix_Assembler_Files(Assem_Dir);
ENDL = '\n';
fprintf(fid, ['// matrix assembler', ENDL]);
fprintf(fid, ['#include "./', obj.Sub_Dir.Assembler, '/FEL_Assembler.h"', ENDL]);
status = write_assembler_files(obj,Assem_Dir,'FEL_Assembler.h',Matrix_Assembler_Files);
fprintf(fid, ['', ENDL]);
end
function status = write_assembler_files(obj,Dir,hdr_h,Matrix_Assembler_Files)
ENDL = '\n';
WRITE_File = fullfile(Dir, hdr_h);
% open file for writing
fid = fopen(WRITE_File, 'a');
fprintf(fid, ['/*', ENDL]);
fprintf(fid, ['============================================================================================', ENDL]);
fprintf(fid, [' Contents are matrix assembler files written by David Bindel.', ENDL]);
fprintf(fid, ['============================================================================================', ENDL]);
fprintf(fid, ['*/', ENDL]);
fprintf(fid, ['', ENDL]);
obj.Write_Preprocessor_Include_Lines(fid,Matrix_Assembler_Files);
fprintf(fid, ['/***/', ENDL]);
status = fclose(fid);
end
|
github
|
eardi/sm-fpca-master
|
Gen_Misc_Math.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Super_Classes/Ghost_Writers/@Generic_GenFELCode/Gen_Misc_Math.m
| 1,589 |
utf_8
|
a295c1631e3e8e024888f570bf338a9e
|
function Gen_Misc_Math(obj,fid)
%Gen_Misc_Math
%
% This generates a section of Misc_Stuff.h: the basic math code.
% fid = an (open) file ID to "Misc_Stuff.h".
% Copyright (c) 06-13-2014, Shawn W. Walker
% copy some standard files over
FC = FELCodeHdr();
% copy over rudimentary structs and math stuff
obj.Make_SubDir(obj.Sub_Dir.Math);
Math_Dir = fullfile(obj.Output_Dir, obj.Sub_Dir.Math);
Linear_Algebra_Files = FC.Copy_Linear_Algebra_Files(Math_Dir);
Geo_Comp_Files = FC.Copy_Geometry_Files(Math_Dir);
ENDL = '\n';
fprintf(fid, ['// useful math structures', ENDL]);
fprintf(fid, ['#include "./', obj.Sub_Dir.Math, '/FEL_Math_Structs.h"', ENDL]);
status = write_math_files(obj,Math_Dir,'FEL_Math_Structs.h',Linear_Algebra_Files,Geo_Comp_Files);
fprintf(fid, ['', ENDL]);
end
function status = write_math_files(obj,Dir,hdr_h,Linear_Algebra_Files,Geo_Comp_Files)
ENDL = '\n';
WRITE_File = fullfile(Dir, hdr_h);
% open file for writing
fid = fopen(WRITE_File, 'a');
fprintf(fid, ['/*', ENDL]);
fprintf(fid, ['============================================================================================', ENDL]);
fprintf(fid, [' Rudimentary math structures.', ENDL]);
fprintf(fid, ['============================================================================================', ENDL]);
fprintf(fid, ['*/', ENDL]);
fprintf(fid, ['', ENDL]);
obj.Write_Preprocessor_Include_Lines(fid,Linear_Algebra_Files);
obj.Write_Preprocessor_Include_Lines(fid,Geo_Comp_Files);
fprintf(fid, ['/***/', ENDL]);
status = fclose(fid);
end
|
github
|
eardi/sm-fpca-master
|
Gen_Misc_Domain_Classes.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Super_Classes/Ghost_Writers/@Generic_GenFELCode/Gen_Misc_Domain_Classes.m
| 1,559 |
utf_8
|
0a9ad7e7a0341d40e3f9c79984ac5f5f
|
function Gen_Misc_Domain_Classes(obj,fid,GeomFunc)
%Gen_Misc_Domain_Classes
%
% This generates a section of Misc_Stuff.h: the domain class files.
% fid = an (open) file ID to "Misc_Stuff.h".
% Copyright (c) 06-13-2014, Shawn W. Walker
% copy some standard files over
FC = FELCodeHdr();
% mesh domains
obj.Make_SubDir(obj.Sub_Dir.Domains);
Domains_Dir = fullfile(obj.Output_Dir, obj.Sub_Dir.Domains);
ENDL = '\n';
fprintf(fid, ['// mesh domain class files', ENDL]);
fprintf(fid, ['#include "./', obj.Sub_Dir.Domains, '/ALL_Domains.h"', ENDL]);
status = write_domain_files(Domains_Dir,'ALL_Domains.h',GeomFunc);
fprintf(fid, ['', ENDL]);
end
function status = write_domain_files(Dir,hdr_h,GeomFunc)
ENDL = '\n';
WRITE_File = fullfile(Dir, hdr_h);
% open file for writing
fid = fopen(WRITE_File, 'a');
fprintf(fid, ['/*', ENDL]);
fprintf(fid, ['============================================================================================', ENDL]);
fprintf(fid, [' Mesh domain class files.', ENDL]);
fprintf(fid, ['============================================================================================', ENDL]);
fprintf(fid, ['*/', ENDL]);
fprintf(fid, ['', ENDL]);
fprintf(fid, ['#include "Abstract_Domain_Class.cc"', ENDL]);
Num_GeomFunc = length(GeomFunc);
for ind=1:Num_GeomFunc
CPP = GeomFunc{ind}.Domain.Determine_CPP_Info;
fprintf(fid,['#include "', CPP.Data_Type_Name_cc, '"', ENDL]);
end
fprintf(fid, ['', ENDL]);
fprintf(fid, ['/***/', ENDL]);
status = fclose(fid);
end
|
github
|
eardi/sm-fpca-master
|
Gen_Misc_Geometry_Classes.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Code_Generation/Super_Classes/Ghost_Writers/@Generic_GenFELCode/Gen_Misc_Geometry_Classes.m
| 1,582 |
utf_8
|
a153098fbfaf70f27401fcfe442c0ffe
|
function Gen_Misc_Geometry_Classes(obj,fid,GeomFunc)
%Gen_Misc_Geometry_Classes
%
% This generates a section of Misc_Stuff.h: the mesh geometry class files.
% fid = an (open) file ID to "Misc_Stuff.h".
% Copyright (c) 06-13-2014, Shawn W. Walker
% copy some standard files over
FC = FELCodeHdr();
% mesh geometry
obj.Make_SubDir(obj.Sub_Dir.Geometry);
Geometry_Dir = fullfile(obj.Output_Dir, obj.Sub_Dir.Geometry);
ENDL = '\n';
fprintf(fid, ['// mesh geometry class files', ENDL]);
fprintf(fid, ['#include "./', obj.Sub_Dir.Geometry, '/ALL_Mesh_Geometry.h"', ENDL]);
status = write_geometry_files(Geometry_Dir,'ALL_Mesh_Geometry.h',GeomFunc);
fprintf(fid, ['', ENDL]);
end
function status = write_geometry_files(Dir,hdr_h,GeomFunc)
ENDL = '\n';
WRITE_File = fullfile(Dir, hdr_h);
% open file for writing
fid = fopen(WRITE_File, 'a');
fprintf(fid, ['/*', ENDL]);
fprintf(fid, ['============================================================================================', ENDL]);
fprintf(fid, [' Mesh geometry class files.', ENDL]);
fprintf(fid, ['============================================================================================', ENDL]);
fprintf(fid, ['*/', ENDL]);
fprintf(fid, ['', ENDL]);
fprintf(fid, ['#include "Abstract_Mesh_Geometry_Class.cc"', ENDL]);
Num_GeomFunc = length(GeomFunc);
for ind = 1:Num_GeomFunc
FN = GeomFunc{ind}.CPP.Data_Type_Name_cc;
fprintf(fid, ['#include "', FN, '"', ENDL]);
end
fprintf(fid, ['', ENDL]);
fprintf(fid, ['/***/', ENDL]);
status = fclose(fid);
end
|
github
|
eardi/sm-fpca-master
|
Compute_Cut_Points.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Static_Codes/Isosurface_Meshing/@Mesher2Dmex/private/Compute_Cut_Points.m
| 2,770 |
utf_8
|
66a6322116b5a7304b531867f2dcd951
|
function cut_pts = Compute_Cut_Points(obj,Interp_Func,Edge_Tail_Point,Edge_Head_Point)
%Compute_Cut_Points
%
% This computes a cut point for each cut edge.
% Copyright (c) 02-10-2018, Shawn W. Walker
TOL = obj.Tolerance;
if obj.Use_Newton
cut_pts = get_cut_point_newton(Interp_Func,Edge_Tail_Point,Edge_Head_Point,TOL);
else
cut_pts = get_cut_point_bisection(Interp_Func,Edge_Tail_Point,Edge_Head_Point,TOL);
end
end
function pt = get_cut_point_bisection(Interp_Func,X0,X1,TOL)
t_win = [zeros(size(X0,1),1), ones(size(X0,1),1)]; % [a, b]
f_a = Interp_Func(X0); % f(a)
f_b = Interp_Func(X1); % f(b)
zero_mask_a = (f_a==0); % f(a)==0
zero_mask_b = (f_b==0); % f(b)==0
t_win(zero_mask_a,2) = t_win(zero_mask_a,1); % set b := a here
t_win(zero_mask_b,1) = t_win(zero_mask_b,2); % set a := b here
COUNT = 0;
while (max(t_win(:,2) - t_win(:,1)) > TOL) % tolerance is ``normalized''
COUNT = COUNT + 1;
if (COUNT > 50)
error('Bisection is not converging!');
end
% compute mid point: c
t = 0.5 * (t_win(:,1) + t_win(:,2)); % get the midpoint
MID_PT(:,1) = X0(:,1).*(1-t) + X1(:,1).*t;
MID_PT(:,2) = X0(:,2).*(1-t) + X1(:,2).*t;
f_c = Interp_Func(MID_PT);
% if we get lucky...
zero_mask_c = (f_c==0); % f(c)==0
% make window [c, c]
t_win(zero_mask_c,1) = t(zero_mask_c);
t_win(zero_mask_c,2) = t(zero_mask_c);
% at this point, we don't need to consider cases where the sign is zero!
% if sign(f(c)) = sign(f(a)) then a := c else b := c
DECISION = (sign(f_c) == sign(f_a));
t_win(DECISION,1) = t(DECISION); % a := c
t_win(~DECISION,2) = t(~DECISION); % b := c
% update f(a)
f_a(DECISION,1) = f_c(DECISION,1);
end
disp('Bisection Finished!');
pt = 0*X0;
t = 0.5 * (t_win(:,1) + t_win(:,2));
pt(:,1) = X0(:,1).*(1-t) + X1(:,1).*t;
pt(:,2) = X0(:,2).*(1-t) + X1(:,2).*t;
end
function pt = get_cut_point_newton(Interp_Func,X0,X1,TOL)
t = 0.5 * ones(size(X0,1),1);
f = ones(size(X0,1),1);
TEMP_PT = 0*X0;
COUNT = 0;
while (max(abs(f)) > TOL)
COUNT = COUNT + 1;
if (COUNT > 20)
error('Newton Method is not converging!');
end
TOO_BIG = (t >= 1);
TOO_SMALL = (t <= 0);
t(TOO_BIG) = 1;
t(TOO_SMALL) = 0;
TEMP_PT(:,1) = X0(:,1).*(1-t) + X1(:,1).*t;
TEMP_PT(:,2) = X0(:,2).*(1-t) + X1(:,2).*t;
[f, grad_phi] = Interp_Func(TEMP_PT);
f_deriv = dot(grad_phi,X1-X0,2);
mf = min(abs(f_deriv));
if (mf==0)
error('Derivative is zero. Not allowed!');
end
t = t - (f./f_deriv);
end
disp('Newton Method Finished!');
pt = 0*X0;
pt(:,1) = X0(:,1).*(1-t) + X1(:,1).*t;
pt(:,2) = X0(:,2).*(1-t) + X1(:,2).*t;
end
|
github
|
eardi/sm-fpca-master
|
Compute_Angles.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Static_Codes/Isosurface_Meshing/@Mesher2Dmex/private/Compute_Angles.m
| 835 |
utf_8
|
2e47f6c0a090ec72d27a1da515174090
|
function A = Compute_Angles(p,t)
%Compute_Angles
%
% 2-D Mesh: A = Tx3 matrix, where each row contains the 3 interior
% angles of a single triangle in the mesh. The angles are
% ordered with respect to the (local) vertex index.
% Angles are given in radians!
% Copyright (c) 10-13-2011, Shawn W. Walker
X2_X1 = p(t(:,2),:) - p(t(:,1),:);
X3_X1 = p(t(:,3),:) - p(t(:,1),:);
X3_X2 = p(t(:,3),:) - p(t(:,2),:);
X2_X1 = normalize(X2_X1);
X3_X1 = normalize(X3_X1);
X3_X2 = normalize(X3_X2);
theta_1 = acos( dot(X2_X1,X3_X1,2) );
theta_2 = acos( dot(X3_X2,-X2_X1,2) );
theta_3 = acos( dot(-X3_X1,-X3_X2,2) );
A = [theta_1, theta_2, theta_3];
end
function V = normalize(V)
V_norm = sqrt(sum(V.^2,2));
for ind=1:size(V,2)
V(:,ind) = V(:,ind) ./ V_norm;
end
end
|
github
|
eardi/sm-fpca-master
|
Compute_Cut_Points.m
|
.m
|
sm-fpca-master/FELICITY_Ver1.3.1/FELICITY/Static_Codes/Isosurface_Meshing/@Mesher3Dmex/private/Compute_Cut_Points.m
| 2,947 |
utf_8
|
35278f478d47ee0dba388815007ebd05
|
function cut_pts = Compute_Cut_Points(obj,Interp_Func,Edge_Tail_Point,Edge_Head_Point)
%Compute_Cut_Points
%
% This computes a cut point for each cut edge.
% Copyright (c) 02-10-2018, Shawn W. Walker
TOL = obj.Tolerance;
if obj.Use_Newton
cut_pts = get_cut_point_newton(Interp_Func,Edge_Tail_Point,Edge_Head_Point,TOL);
else
cut_pts = get_cut_point_bisection(Interp_Func,Edge_Tail_Point,Edge_Head_Point,TOL);
end
end
function pt = get_cut_point_bisection(Interp_Func,X0,X1,TOL)
t_win = [zeros(size(X0,1),1), ones(size(X0,1),1)]; % [a, b]
f_a = Interp_Func(X0); % f(a)
f_b = Interp_Func(X1); % f(b)
zero_mask_a = (f_a==0); % f(a)==0
zero_mask_b = (f_b==0); % f(b)==0
t_win(zero_mask_a,2) = t_win(zero_mask_a,1); % set b := a here
t_win(zero_mask_b,1) = t_win(zero_mask_b,2); % set a := b here
COUNT = 0;
while (max(t_win(:,2) - t_win(:,1)) > TOL) % tolerance is ``normalized''
COUNT = COUNT + 1;
if (COUNT > 50)
error('Bisection is not converging!');
end
% compute mid point: c
t = 0.5 * (t_win(:,1) + t_win(:,2)); % get the midpoint
MID_PT(:,1) = X0(:,1).*(1-t) + X1(:,1).*t;
MID_PT(:,2) = X0(:,2).*(1-t) + X1(:,2).*t;
MID_PT(:,3) = X0(:,3).*(1-t) + X1(:,3).*t;
f_c = Interp_Func(MID_PT);
% if we get lucky...
zero_mask_c = (f_c==0); % f(c)==0
% make window [c, c]
t_win(zero_mask_c,1) = t(zero_mask_c);
t_win(zero_mask_c,2) = t(zero_mask_c);
% at this point, we don't need to consider cases where the sign is zero!
% if sign(f(c)) = sign(f(a)) then a := c else b := c
DECISION = (sign(f_c) == sign(f_a));
t_win(DECISION,1) = t(DECISION); % a := c
t_win(~DECISION,2) = t(~DECISION); % b := c
% update f(a)
f_a(DECISION,1) = f_c(DECISION,1);
end
disp('Bisection Finished!');
pt = 0*X0;
t = 0.5 * (t_win(:,1) + t_win(:,2));
pt(:,1) = X0(:,1).*(1-t) + X1(:,1).*t;
pt(:,2) = X0(:,2).*(1-t) + X1(:,2).*t;
pt(:,3) = X0(:,3).*(1-t) + X1(:,3).*t;
end
function pt = get_cut_point_newton(Interp_Func,X0,X1,TOL)
t = 0.5 * ones(size(X0,1),1);
f = ones(size(X0,1),1);
TEMP_PT = 0*X0;
COUNT = 0;
while (max(abs(f)) > TOL)
COUNT = COUNT + 1;
if (COUNT > 20)
error('Newton Method is not converging!');
end
TOO_BIG = (t >= 1);
TOO_SMALL = (t <= 0);
t(TOO_BIG) = 1;
t(TOO_SMALL) = 0;
TEMP_PT(:,1) = X0(:,1).*(1-t) + X1(:,1).*t;
TEMP_PT(:,2) = X0(:,2).*(1-t) + X1(:,2).*t;
TEMP_PT(:,3) = X0(:,3).*(1-t) + X1(:,3).*t;
[f, grad_phi] = Interp_Func(TEMP_PT);
f_deriv = dot(grad_phi,X1-X0,2);
mf = min(abs(f_deriv));
if (mf==0)
error('Derivative is zero. Not allowed!');
end
t = t - (f./f_deriv);
end
disp('Newton Method Finished!');
pt = 0*X0;
pt(:,1) = X0(:,1).*(1-t) + X1(:,1).*t;
pt(:,2) = X0(:,2).*(1-t) + X1(:,2).*t;
pt(:,3) = X0(:,3).*(1-t) + X1(:,3).*t;
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.