Related
I have a pure function that takes 18 arguments process them and returns an answer.
Inside this function I call many other pure functions and those functions call other pure functions within them as deep as 6 levels.
This way of composition is cumbersome to test as the top level functions,in addition to their logic,have to gather parameters for inner functions.
# Minimal conceptual example
main_function(a, b, c, d, e) = begin
x = pure_function_1(a, b, d)
y = pure_function_2(a, c, e, x)
z = pure_function_3(b, c, y, x)
answer = pure_function_4(x,y,z)
return answer
end
# real example
calculate_time_dependant_losses(
Ap,
u,
Ac,
e,
Ic,
Ep,
Ecm_t,
fck,
RH,
T,
cementClass::Char,
ρ_1000,
σ_p_start,
f_pk,
t0,
ts,
t_start,
t_end,
) = begin
μ = σ_p_start / f_pk
fcm = fck + 8
Fr = σ_p_start * Ap
_σ_pb = σ_pb(Fr, Ac, e, Ic)
_ϵ_cs_t_start_t_end = ϵ_cs_ti_tj(ts, t_start, t_end, Ac, u, fck, RH, cementClass)
_ϕ_t0_t_start_t_end = ϕ_t0_ti_tj(RH, fcm, Ac, u, T, cementClass, t0, t_start, t_end)
_Δσ_pr_t_start_t_end =
Δσ_pr(σ_p_start, ρ_1000, t_end, μ) - Δσ_pr(σ_p_start, ρ_1000, t_start, μ)
denominator =
1 +
(1 + 0.8 * _ϕ_t0_t_start_t_end) * (1 + (Ac * e^2) / Ic) * ((Ep * Ap) / (Ecm_t * Ac))
shrinkageLoss = (_ϵ_cs_t_start_t_end * Ep) / denominator
relaxationLoss = (0.8 * _Δσ_pr_t_start_t_end) / denominator
creepLoss = (Ep * _ϕ_t0_t_start_t_end * _σ_pb) / Ecm_t / denominator
return shrinkageLoss + relaxationLoss + creepLoss
end
I see examples of functional composition (dot chaining,pipe operator etc) with single argument functions.
Is it practical to compose the above function using functional programming?If yes, how?
The standard and simple way is to recast your example so that it can be written as
# Minimal conceptual example, re-cast
main_function(a, b, c, d, e) = begin
x = pure_function_1'(a, b, d)()
y = pure_function_2'(a, c, e)(x)
z = pure_function_3'(b, c)(y) // I presume you meant `y` here
answer = pure_function_4(z) // and here, z
return answer
end
Meaning, we use functions that return functions of one argument. Now these functions can be easily composed, using e.g. a forward-composition operator (f >>> g)(x) = g(f(x)) :
# Minimal conceptual example, re-cast, composed
main_function(a, b, c, d, e) = begin
composed_calculation =
pure_function_1'(a, b, d) >>>
pure_function_2'(a, c, e) >>>
pure_function_3'(b, c, y) >>>
pure_function_4
answer = composed_calculation()
return answer
end
If you really need the various x y and z at differing points in time during the composed computation, you can pass them around in a compound, record-like data structure. We can avoid the coupling of this argument handling if we have extensible records:
# Minimal conceptual example, re-cast, composed, args packaged
main_function(a, b, c, d, e) = begin
composed_calculation =
pure_function_1'(a, b, d) >>> put('x') >>>
get('x') >>> pure_function_2'(a, c, e) >>> put('y') >>>
get('x') >>> pure_function_3'(b, c, y) >>> put('z') >>>
get({'x';'y';'z'}) >>> pure_function_4
answer = composed_calculation(empty_initial_state)
return value(answer)
end
The passed around "state" would be comprised of two fields: a value and an extensible record. The functions would accept this state, use the value as their additional input, and leave the record unchanged. get would take the specified field out of the record and put it in the "value" field in the state. put would mutate the extensible record in the state:
put(field_name) = ( {value:v ; record:r} =>
{v ; put_record_field( r, field_name, v)} )
get(field_name) = ( {value:v ; record:r} =>
{get_record_field( r, field_name) ; r} )
pure_function_2'(a, c, e) = ( {value:v ; record:r} =>
{pure_function_2(a, c, e, v); r} )
value(r) = get_record_field( r, value)
empty_initial_state = { novalue ; empty_record }
All in pseudocode.
Augmented function application, and hence composition, is one way of thinking about "what monads are". Passing around the pairing of a produced/expected argument and a state is known as State Monad. The coder focuses on dealing with the values while treating the state as if "hidden" "under wraps", as we do here through the get/put etc. facilities. Under this illusion/abstraction, we do get to "simply" compose our functions.
I can make a small start at the end:
sum $ map (/ denominator)
[ _ϵ_cs_t_start_t_end * Ep
, 0.8 * _Δσ_pr_t_start_t_end
, (Ep * _ϕ_t0_t_start_t_end * _σ_pb) / Ecm_t
]
As mentioned in the comments (repeatedly), the function composition operator does indeed accept multiple argument functions. Cite: https://docs.julialang.org/en/v1/base/base/#Base.:%E2%88%98
help?> ∘
"∘" can be typed by \circ<tab>
search: ∘
f ∘ g
Compose functions: i.e. (f ∘ g)(args...; kwargs...) means f(g(args...; kwargs...)). The ∘ symbol
can be entered in the Julia REPL (and most editors, appropriately configured) by typing
\circ<tab>.
Function composition also works in prefix form: ∘(f, g) is the same as f ∘ g. The prefix form
supports composition of multiple functions: ∘(f, g, h) = f ∘ g ∘ h and splatting ∘(fs...) for
composing an iterable collection of functions.
The challenge is chaining the operations together, because any function can only pass on a tuple to the next function in the composed chain. The solution could be making sure your chained functions 'splat' the input tuples into the next function.
Example:
# splat to turn max into a tuple-accepting function
julia> f = (x->max(x...)) ∘ minmax;
julia> f(3,5)
5
Using this will in no way help make your function cleaner, though, in fact it will probably make a horrible mess.
Your problems do not at all seem to me to be related to how you call, chain or compose your functions, but are entirely due to not organizing the inputs in reasonable types with clean interfaces.
Edit: Here's a custom composition operator that splats arguments, to avoid the tuple output issue, though I don't see how it can help picking the right arguments, it just passes everything on:
⊕(f, g) = (args...) -> f(g(args...)...)
⊕(f, g, h...) = ⊕(f, ⊕(g, h...))
Example:
julia> myrev(x...) = reverse(x);
julia> (myrev ⊕ minmax)(5,7)
(7, 5)
julia> (minmax ⊕ myrev ⊕ minmax)(5,7)
(5, 7)
Good time of the day!
Here is the code:
eq:'diff(x,t)=(exp(cos(t))-1)*x;
ode2(eq,x,t);
sol:ic1(%,t=1,x=-1);
/*---------------------*/
plot2d(
rhs(sol),
[t,-4*%pi, 4*%pi],
[y,-5,5],
[xtics,-4*%pi, 1*%pi, 4*%pi],
[ytics, false],
/*[yx_ratio , 0.6], */
[legend,"Solution."],
[xlabel, "t"], [ylabel, "x(t)"],
[style, [lines,1]],
[color, blue]
);
and here is the errors:
integrate: variable must not be a number; found: -12.56637061435917
What went wrong?
Thanks.
Here's a way to plot the solution sol which was found by ode2 and ic2 as you showed. First replace the integrate nouns with calls to quad_qags, a numerical quadrature function. I'll introduce a made-up variable name (a so-called gensym) to avoid confusion with the variable t.
(%i59) subst (nounify (integrate) =
lambda ([e, xx],
block ([u: gensym(string(xx))],
quad_qags (subst (xx = u, e), u, -4*%pi, xx)[1])),
rhs(sol));
(%o59) -%e^((-t)-quad_qags(%e^cos(t88373),t88373,-4*%pi,t,
epsrel = 1.0E-8,epsabs = 0.0,
limit = 200)[
1]
+quad_qags(%e^cos(t88336),t88336,-4*%pi,t,
epsrel = 1.0E-8,epsabs = 0.0,
limit = 200)[
1]+1)
Now I'll define a function foo1 with that result. I'll make a list of numerical values to see if it works right.
(%i60) foo1(t) := ''%;
(%o60) foo1(t):=-%e
^((-t)-quad_qags(%e^cos(t88373),t88373,-4*%pi,t,
epsrel = 1.0E-8,epsabs = 0.0,
limit = 200)[
1]
+quad_qags(%e^cos(t88336),t88336,-4*%pi,t,
epsrel = 1.0E-8,epsabs = 0.0,
limit = 200)[
1]+1)
(%i61) foo1(0.5);
(%o61) -1.648721270700128
(%i62) makelist (foo1(t), t, makelist (k, k, -10, 10));
(%o62) [-59874.14171519782,-22026.46579480672,
-8103.083927575384,-2980.957987041728,
-1096.633158428459,-403.4287934927351,
-148.4131591025766,-54.59815003314424,
-20.08553692318767,-7.38905609893065,-2.71828182845904,
-1.0,-0.3678794411714423,-0.1353352832366127,
-0.04978706836786394,-0.01831563888873418,
-0.006737946999085467,-0.002478752176666358,
-9.118819655545163E-4,-3.354626279025119E-4,
-1.234098040866796E-4]
Does %o62 look right to you? I'll assume it is okay. Next I'll define a function foo which calls foo1 defined before when the argument is a number, otherwise it just returns 0. This is a workaround for a bug in plot2d, which incorrectly determines that foo1 is not a function of t alone. Usually that workaround isn't needed, but it is needed in this case.
(%i63) foo(t) := if numberp(t) then foo1(t) else 0;
(%o63) foo(t):=if numberp(t) then foo1(t) else 0
Okay, now the function foo can be plotted!
(%i64) plot2d (foo, [t, -4*%pi, 4*%pi], [y, -5, 5]);
plot2d: some values were clipped.
(%o64) false
That takes about 30 seconds to plot -- calling quad_qags is relatively expensive.
it looks like ode2 does not know how to completely solve the problem, so the result contains an integral:
(%i6) display2d: false $
(%i7) eq:'diff(x,t)=(exp(cos(t))-1)*x;
(%o7) 'diff(x,t,1) = (%e^cos(t)-1)*x
(%i8) ode2(eq,x,t);
(%o8) x = %c*%e^('integrate(%e^cos(t),t)-t)
(%i9) sol:ic1(%,t=1,x=-1);
(%o9) x = -%e^((-%at('integrate(%e^cos(t),t),t = 1))
+'integrate(%e^cos(t),t)-t+1)
I tried it with contrib_ode also:
(%i12) load (contrib_ode);
(%o12) "/Users/dodier/tmp/maxima-code/share/contrib/diffequations/contrib_ode.mac"
(%i13) contrib_ode (eq, x, t);
(%o13) [x = %c*%e^('integrate(%e^cos(t),t)-t)]
So contrib_ode did not solve it completely either.
However the solution returned by ode2 (same for contrib_ode) appears to be a valid solution. I'll post a separate answer describing how to evaluate it numerically for plotting.
I have the image and the vector
a = imread('Lena.tiff');
v = [0,2,5,8,10,12,15,20,25];
and this M-file
function y = Funks(I, gama, c)
[m n] = size(I);
for i=1:m
for j=1:n
J(i, j) = (I(i, j) ^ gama) * c;
end
end
y = J;
imshow(y);
when I'm trying to do this:
f = Funks(a,v,2)
I am getting this error:
??? Error using ==> mpower
Integers can only be combined with integers of the same class, or scalar doubles.
Error in ==> Funks at 5
J(i, j) = (I(i, j) ^ gama) * c;
Can anybody help me, with this please?
The error is caused because you're trying to raise a number to a vector power. Translated (i.e. replacing formal arguments with actual arguments in the function call), it would be something like:
J(i, j) = (a(i, j) ^ [0,2,5,8,10,12,15,20,25]) * 2
Element-wise power .^ won't work either, because you'll try to "stuck" a vector into a scalar container.
Later edit: If you want to apply each gamma to your image, maybe this loop is more intuitive (though not the most efficient):
a = imread('Lena.tiff'); % Pics or GTFO
v = [0,2,5,8,10,12,15,20,25]; % Gamma (ar)ray -- this will burn any picture
f = cell(1, numel(v)); % Prepare container for your results
for k=1:numel(v)
f{k} = Funks(a, v(k), 2); % Save result from your function
end;
% (Afterwards you use cell array f for further processing)
Or you may take a look at the other (more efficient if maybe not clearer) solutions posted here.
Later(er?) edit: If your tiff file is CYMK, then the result of imread is a MxNx4 color matrix, which must be handled differently than usual (because it 3-dimensional).
There are two ways I would follow:
1) arrayfun
results = arrayfun(#(i) I(:).^gama(i)*c,1:numel(gama),'UniformOutput',false);
J = cellfun(#(x) reshape(x,size(I)),results,'UniformOutput',false);
2) bsxfun
results = bsxfun(#power,I(:),gama)*c;
results = num2cell(results,1);
J = cellfun(#(x) reshape(x,size(I)),results,'UniformOutput',false);
What you're trying to do makes no sense mathematically. You're trying to assign a vector to a number. Your problem is not the MATLAB programming, it's in the definition of what you're trying to do.
If you're trying to produce several images J, each of which corresponds to a certain gamma applied to the image, you should do it as follows:
function J = Funks(I, gama, c)
[m n] = size(I);
% get the number of images to produce
k = length(gama);
% Pre-allocate the output
J = zeros(m,n,k);
for i=1:m
for j=1:n
J(i, j, :) = (I(i, j) .^ gama) * c;
end
end
In the end you will get images J(:,:,1), J(:,:,2), etc.
If this is not what you want to do, then figure out your equations first.
I've got some fairly long matrix algebra that I am trying to plot the outcome of. Nothing seems to show up on the axes, and I can't quite tell where the problem is. I successfully created a function from the output of solve using the tips here:
How to create a function directly from the output of Solve
But it just won't plot!
Here (briefly) is the code:
eqn = m.{1, r} == {t, 0}
sols1 = Solve[eqn, {t, r}]
m is a complex matrix
Here is the output:
{{t -> -((-1. cos[9.62458 s]^2 - (1. + 0. I) sin[9.62458 s]^2)/(
cos[9.62458 s] - (0. + 2.4087 I) sin[9.62458 s])),
r -> ((0. + 2.1913 I) sin[9.62458 s])/(
cos[9.62458 s] - (0. + 2.4087 I) sin[9.62458 s])}}
So far so good (except that Mathematica seems to have trouble with the whole cos^2 + sin^2 = 1 thing).
Then I try to plot the real part of t as a function of s:
Plot[Re[t /. sols1], {s, 0, 0.4}]
And I just get empty axes.
I try assigning the output to a function and plotting that way
f[s_] = t /. sols1[[1, 1]]
Plot[Re[f[s]], {s, 0, 0.4}]
And I still get an empty axis. I transcribed the function in Matlab where it plots just fine, so I know the solution is sound. I have to solve this for several matrices m which just get hairier and hairier, so transcribing to Matlab is not ideal. I want to plot right in Mathematica.
Any ideas?
Try using mathematica syntax. I.e. Sin in place of sin; same for cos:
In[1]:= sols1={
{t->-((-1. cos[9.62458 s]^2-(1.+0. I) sin[9.62458 s]^2)/(cos[9.62458 s]-(0.+2.4087 I) sin[9.62458 s]))
,r->((0.+2.1913 I) sin[9.62458 s])/(cos[9.62458 s]-(0.+2.4087 I) sin[9.62458 s])}
}/.{cos->Cos,sin->Sin}//FullSimplify//Chop
Out[1]= {{t->1./(Cos[9.62458 s]-(0. +2.4087 I) Sin[9.62458 s]),r->1/(-1.09921-(0. +0.45635 I) Cot[9.62458 s])}}
then e.g.
GraphicsColumn[Plot[t /. sols1 // #, {s, 0, .4}, PlotLabel -> #[t], Frame -> True] & /# {Re, Im, Abs[#]^2 &}]
should work well.
I've figured out how to display the repeating part of a repeating decimal using OverBar.
repeatingDecimal doesn't actually work as a repeating decimal. I'd like to make a variation of it that looks and behaves like a repeating decimal.
Question
How could I make a working repeating decimal representation (possibly using Interpretation[])?
Background
Please excuse me if I ramble. This is my first question and I wanted to be clear about what I have in mind.
The following will "draw" a repeating decimal.
repeatingDecimal[q2_] :=
Module[{a},
a[{{nr__Integer}, pt_}] :=
StringJoin[
Map[ToString,
If[pt > -1, Insert[{nr}, ".", pt + 1],
Join[{"."}, Table["0", {Abs[pt]}], {nr}]]]];
(* repeating only *)
a[{{{r__Integer}}, pt_}] :=
Row[{".", OverBar#StringJoin[Map[ToString, {r}]]}];
(* One or more non-repeating;
more than one repeating digit KEEP IN THIS ORDER!! *)
a[{{nr__, {r__}}, pt_}] :=
Row[{StringJoin[
Map[ToString,
If[pt > -1, Insert[{nr}, ".", pt + 1],
Join[{"."}, Table["0", {Abs[pt]}], {nr}]]]],
OverBar#StringJoin[Map[ToString, {r}]]}];
(* One or more non-repeating; one repeating digit *)
a[{{nr__, r_Integer}, pt_}] :=
Row[{StringJoin[Map[ToString, {nr}]], ".",
OverBar#StringJoin[Map[ToString, r]]}];
a[RealDigits[q2]]]
So
repeatingDecimal[7/31]
displays a repeating decimal properly (shown here as a picture so that the OverBar appears).
Looking under the hood, it's really just an imposter, an image of a repeating decimal ...
In[]:= repeatingDecimal[7/31]//FullForm
Out[]:= Row[List[".",OverBar["225806451612903"]]]
Of course, it doesn't behave like a number:
% + 24/31
I'd like the addition to yield: 1
Edit: A cleaned up version of repeatingDecimal
Leonid showed how to wrap Format around the routine and to supply up-values for adding and multiplying repeated decimals. Very helpful! It will take some time for me to be comfortable with up and down values.
What follows below is essentially the streamlined version of the code suggested by Mr.Wizard. I set the OverBar above each repeating digit to allow line-breaking. (A single OverBar above Row looks tidier but cannot break when the right screen-margin is reached.)
ClearAll[repeatingDecimal]
repeatingDecimal[n_Integer | n_Real] := n
Format[repeatingDecimal[q_Rational]] := Row # Flatten[
{IntegerPart#q, ".", RealDigits#FractionalPart#q} /.
{{nr___Integer, r_List: {}}, pt_} :> {Table[0, {-pt}], nr, OverBar /# r}
]
repeatingDecimal[q_] + x_ ^:= q + x
repeatingDecimal[q_] * x_ ^:= q * x
repeatingDecimal[q_] ^ x_ ^:= q ^ x
The table below shows some output from repeatingDecimal:
n1 = 1; n2 = 15; ClearAll[i, k, r];
TableForm[Table[repeatingDecimal[i/j], {i, n1, n2}, {j, n1, n2}],
TableHeadings -> {None, Table[("r")/k, {k, n1, n2}]}]
Checking the solution: Operating with repeating decimals
Let's now check the addition and multiplication of repeating decimals:
a = repeatingDecimal[7/31];
b = repeatingDecimal[24/31];
Print["a = ", a]
Print["b = ", b]
Print["a + b = ", a, " + ", b, " = ", a + b]
Print["7/31 \[Times] 24/31 = " , (7/31)* (24/31)]
Print["a\[Times]b = ", a*b, " = \n", repeatingDecimal[a*b]]
Print[N[168/961, 465]]
So addition and multiplication of repeating decimals work as desired. Power also appears to work properly.
Notice that 168/961 occupies 465 places to the right of the decimal point. After that, it starts to repeat. The results match those of N[168/961, 465], except for the OverBar, although line-breaks occur at different places. And, as is to be expected, this jibes with the following:
digits = RealDigits[168/961]
Length[digits[[1, 1]]]
Some effects of the Format[] wrapper on the behavior of N[] in summing repeated decimals
Mr.Wizard suggested that the Format wrapper is superfluous for the cases of Integers and Reals.
Let's consider how the following two additions
repeatingDecimal[7/31] + repeatingDecimal[24/31]
N#repeatingDecimal[7/31] + N#repeatingDecimal[24/31]
behave in four different cases:
Case 1: Results when Format wrapped around repeatingDecimals for Reals and Integers and up values are ON
As expected, the first addition yields an integer, the second a decimal.
Case 2: Results when Format NOT wrapped around repeatingDecimals for Reals and Integers but up values are ON
The Format wrapper around Reals and Integers doesn't affect the additions at hand.
Case 3: Results when Format wrapped around repeatingDecimals for Reals and Integers but up values are OFF
If upvalues are OFF, Format prevents addition from happening.
Case 4: Results when Format NOT wrapped around repeatingDecimals for Reals and Integers and up values are OFF
If upvalues are OFF and Format` NOT wrapped around repeatingDecimals for Reals and Integers , the second addition works as expected.
All the more reason to remove the Format wrapper for the case of reals and integers.
Anyone have any remarks about the different outcomes in Cases 3 and 4?
You shouldn't have given your repeatingDecimal DownVaues, but rather, FormatValues:
ClearAll[repeatingDecimal];
Format[repeatingDecimal[q2_]] :=
Module[{a},
a[{{nr__Integer}, pt_}] :=
StringJoin[
Map[ToString,
If[pt > -1, Insert[{nr}, ".", pt + 1],
Join[{"."}, Table["0", {Abs[pt]}], {nr}]]]];
(*repeating only*)
a[{{{r__Integer}}, pt_}] :=
Row[{".", OverBar#StringJoin[Map[ToString, {r}]]}];
(*One or more non-repeating;
more than one repeating digit KEEP IN THIS ORDER!!*)
a[{{nr__, {r__}}, pt_}] :=
Row[{StringJoin[
Map[ToString,
If[pt > -1, Insert[{nr}, ".", pt + 1],
Join[{"."}, Table["0", {Abs[pt]}], {nr}]]]],
OverBar#StringJoin[Map[ToString, {r}]]}];
(*One or more non-repeating;one repeating digit*)
a[{{nr__, r_Integer}, pt_}] :=
Row[{StringJoin[Map[ToString, {nr}]], ".",
OverBar#StringJoin[Map[ToString, r]]}];
a[RealDigits[q2]]]
Then, you can give it also UpValues, to integrate with common functions, for example:
repeatingDecimal /: Plus[left___, repeatingDecimal[q_], right___] := left + q + right;
repeatingDecimal /: Times[left___, repeatingDecimal[q_], right___] := left * q * right;
Then, for example,
In[146]:= repeatingDecimal[7/31]+24/31
Out[146]= 1
You can extend this approach to other common functions which you may want to work with repeatingDecimal.
Here is a possible refactoring of your updated code. I think it works this time (fingers crossed). If you do not need the color highlighting, you can leave off ~Style~ and the rest of that line.
ClearAll[repeatingDecimal];
Format[repeatingDecimal[n_Integer | n_Real]] := n;
Format[repeatingDecimal[q_Rational]] :=
Row[{IntegerPart#q, ".", RealDigits#FractionalPart#q}] /.
{{ nr___Integer, r_List:{} }, pt_} :>
Row#Join[
"0" ~Table~ {-pt},
{nr},
If[r === {}, {}, {OverBar#Row#r}]
] ~Style~ If[r === {}, Blue, If[{nr} === {}, Red, Gray]]
repeatingDecimal /:
(h : Plus | Times)[left___, repeatingDecimal[q_], right___] :=
h[left, q, right];
I will leave this older version here for reference, but I am now making edits to the Question community wiki.