janhardo

820 Reputation

12 Badges

11 years, 218 days

MaplePrimes Activity


These are replies submitted by janhardo

Its not yet similar :-)

@Jean-Michel 

Take another look, but I'm afraid Maple won't be able to achieve the same effect in MMA.

bye
Jan

@Jean-Michel 
I am a dutch , from the Netherlands, yeah :-) 
But what is the intention of you examples ?
Tip:  for better reading your code use : the insert code snippet knob - right next  A , use tooltip too

Try to do something now with the Head construction from MMA and this apply in Maple ?

@Jean-Michel 

I tried to extend the module code with this new expression, but it appears to be impossible to obtain the same result in Maple.

.

# Debug versie - show all found paths
N := [a, a, 1 + a, [[1/a] + a^2, [a]]]:
result := FindPositions:-ModuleApply(N, a, 'explain'=true);
Expression: [a, a, 1+a, [[1/a]+a^2, [a]]]
Looking for: a
Levelspec: infinity
Found at 6 position(s):
1. Path [1]
2. Path [2]
3. Path [3, 2]
4. Path [4, 1, 1, 1, 1]
5. Path [4, 1, 2, 1]
6. Path [4, 2, 1]

  result := [[1], [2], [3, 2], [4, 1, 1, 1, 1], [4, 1, 2, 1], 

    [4, 2, 1]]

@Jean-Michel 

Calulated by module code 

M := [[a], [[a, [a]], a]];
                   M := [[a], [[a, [a]], a]]

FindPositions(M, a);
           [[1, 1], [2, 1, 1], [2, 1, 2, 1], [2, 2]]

Now using module code ...
Findposions_module_5_vb_werken_DEF_22-1-2026_.mw

ah, yes a special bier , i like that too :-)

@sand15 
Thank you for the recommendations. So, I should see if I can interpret them correctly in order to improve this procedure, so that something new comes out of it?

@Jean-Michel 

"maple.ini in user" ,  i  removed it in the code this ( forget to remove)   , it is a initialization for a new worksheet , has nothing to do with the code 
Now it works the  code.

"i'm too tired :) and it's only 9:30 pm" ..what have you done today  :-)

@Jean-Michel 
Hello,
Tried something , but need more testing., but the example works.
I am also investigating using a module structure in Maple to make it easier to program the FindPositions ( ) overload command.

restart;
FindPositions := proc()
    local 
        parse_levelspec,
        should_process_level,
        recursive_search,
        extract_first_n,
        explain_result,
        compare_paths_mathematica,
        
        arg_list, expr, pattern, levelspec, n, heads,
        min_level, max_level, result, i, ls_temp,
        explanation, test_expected, temp_result, item;
    
    arg_list := [args];
    
    if nops(arg_list) < 2 then
        error "FindPositions expects at least 2 arguments: expression and pattern";
    end if;
    
    expr := arg_list[1];
    pattern := arg_list[2];
    
    levelspec := infinity;
    n := infinity;
    heads := false;
    explanation := false;
    test_expected := false;
    
    i := 3;
    while i <= nops(arg_list) do
        if (type(arg_list[i], {integer, list, set, identical(infinity)}) 
           and levelspec = infinity) then
            if type(arg_list[i], set) then
                levelspec := [op(arg_list[i])];
            else
                levelspec := arg_list[i];
            end if;
        elif type(arg_list[i], posint) and n = infinity then
            n := arg_list[i];
        elif type(arg_list[i], 'identical'('heads'='true', 'heads'='false')) then
            heads := op(2, arg_list[i]);
        elif type(arg_list[i], 'equation') and lhs(arg_list[i]) = 'Heads' then
            heads := rhs(arg_list[i]);
        elif type(arg_list[i], 'identical'('explain'='true', 'explain'='false')) then
            explanation := op(2, arg_list[i]);
        elif type(arg_list[i], 'equation') and lhs(arg_list[i]) = 'Explain' then
            explanation := rhs(arg_list[i]);
        elif type(arg_list[i], 'equation') and lhs(arg_list[i]) = 'Test' then
            test_expected := rhs(arg_list[i]);
        else
            error "Invalid argument at position %1: %2", i, arg_list[i];
        end if;
        i := i + 1;
    end do;
    
    # GECORRIGEERDE parse_levelspec die sets accepteert
    parse_levelspec := proc(ls)
    local ls_list;
        if ls = infinity then
            return [0, infinity];
        elif type(ls, integer) and ls >= 0 then
            return [ls, ls];
        elif type(ls, list) then
            if nops(ls) = 1 and type(ls[1], integer) and ls[1] >= 0 then
                return [ls[1], ls[1]];
            elif nops(ls) = 2 and type(ls[1], integer) and ls[1] >= 0 
                 and (ls[2] = infinity or (type(ls[2], integer) and ls[2] >= ls[1])) then
                return [ls[1], ls[2]];
            end if;
        elif type(ls, set) then
            # Converteer set naar list
            ls_list := [op(ls)];
            if nops(ls_list) = 1 and type(ls_list[1], integer) and ls_list[1] >= 0 then
                return [ls_list[1], ls_list[1]];
            elif nops(ls_list) = 2 and type(ls_list[1], integer) and ls_list[1] >= 0 
                 and (ls_list[2] = infinity or (type(ls_list[2], integer) and ls_list[2] >= ls_list[1])) then
                return [ls_list[1], ls_list[2]];
            end if;
        end if;
        error "levelspec must be n, {n}, {m,n}, or Infinity, received: %1", ls;
    end proc;
    
    should_process_level := proc(current, minlvl, maxlvl)
        if current < minlvl then
            return false;
        elif maxlvl = infinity then
            return true;
        else
            return current <= maxlvl;
        end if;
    end proc;
    
    compare_paths_mathematica := proc(a, b)
    local k, min_len;
        min_len := min(nops(a), nops(b));
        
        for k to min_len do
            if a[k] < b[k] then
                return true;
            elif a[k] > b[k] then
                return false;
            end if;
        end do;
        
        return nops(a) < nops(b);
    end proc;
    
    # GECORRIGEERDE recursieve zoekfunctie voor {1,2}
    recursive_search := proc(expr, pattern, minlvl, maxlvl, path, current_level, heads)
    local i, n_items, result, next_level, args_list, term, sub_result, sub;
        result := [];
        
        if expr = pattern and should_process_level(current_level, minlvl, maxlvl) then
            result := [path];
        end if;
        
        if maxlvl <> infinity and current_level >= maxlvl then
            return result;
        end if;
        
        next_level := current_level + 1;
        
        if type(expr, list) then
            n_items := numelems(expr);
            for i to n_items do
                result := [op(result), 
                          op(procname(expr[i], pattern, minlvl, maxlvl, 
                                     [op(path), i], next_level, heads))];
            od;
            
        elif type(expr, `+`) then
            args_list := [op(expr)];
            n_items := numelems(args_list);
            
            # AANPASSING voor {1,2}: bij beperkte niveaus moeten we anders omgaan met sommen
            if maxlvl <> infinity then
                # Voor {1,2}: alleen exacte matches, niet has()
                for i to n_items do
                    term := args_list[i];
                    if term = pattern and should_process_level(next_level, minlvl, maxlvl) then
                        result := [op(result), [op(path), i]];
                    end if;
                od;
            else
                # Voor infinity: gebruik has() voor patronen binnen termen
                for i to n_items do
                    term := args_list[i];
                    
                    if has(term, pattern) and should_process_level(next_level, minlvl, maxlvl) then
                        result := [op(result), [op(path), i]];
                    end if;
                    
                    if maxlvl = infinity or next_level < maxlvl then
                        sub_result := procname(term, pattern, minlvl, maxlvl,
                                              [op(path), i], next_level, heads);
                        for sub in sub_result do
                            result := [op(result), op(sub)];
                        end do;
                    end if;
                od;
            end if;
            
        elif type(expr, `*`) then
            args_list := [op(expr)];
            n_items := numelems(args_list);
            for i to n_items do
                result := [op(result), 
                          op(procname(args_list[i], pattern, minlvl, maxlvl,
                                     [op(path), i], next_level, heads))];
            od;
        end if;
        
        return result;
    end proc;
    
    extract_first_n := proc(results, n)
    local sorted_results;
        if n = infinity or n >= nops(results) then
            return results;
        else
            sorted_results := sort(results, compare_paths_mathematica);
            return sorted_results[1..min(n, nops(sorted_results))];
        end if;
    end proc;
    
    (min_level, max_level) := op(parse_levelspec(levelspec));
    
    result := recursive_search(expr, pattern, min_level, max_level, [], 0, heads);
    
    temp_result := [];
    for item in result do
        if type(item, list) and nops(item) > 0 then
            temp_result := [op(temp_result), item];
        end if;
    end do;
    result := temp_result;
    
    result := convert(convert(result, 'set'), 'list');
    
    result := sort(result, compare_paths_mathematica);
    
    result := extract_first_n(result, n);
    
    if explanation then
        printf("Expression: %a\n", expr);
        printf("Looking for: %a\n", pattern);
        printf("Found at %d position(s):\n", nops(result));
        for i to nops(result) do
            printf("%d. Path %a\n", i, result[i]);
        od;
    end if;
    
    if test_expected <> false then
        if result = test_expected then
            printf("✓ TEST PASSED: Result matches expected output\n");
        else
            printf("✗ TEST FAILED:\n");
            printf("  Expected: %a\n", test_expected);
            printf("  Got:      %a\n", result);
        end if;
    end if;
    
    return result;
end proc:
                   
# TEST 
M := [[1, a], a, [[3 + a]], 2*a - 1]:

# Verify that the other tests still work
printf("\n=============================================\n");
printf("VERIFICATION OF OTHER TESTS:\n");
printf("=============================================\n");

printf("TEST 1: All positions of 'a' in M\n");
result1 := FindPositions(M, a, 'Test' = [[1, 2], [2], [3, 1, 1, 2], [4, 1]]);
printf("Result: %a\n\n", result1);

printf("TEST 2: Level 1 only\n");
result2 := FindPositions(M, a, 1, 'Test' = [[2]]);
printf("Result: %a\n\n", result2);

printf("=============================================\n");
printf("TEST 3 ONLY: Levels 1 and 2\n");
printf("Expected: [[1, 2], [2]]\n");
printf("=============================================\n");
result3 := FindPositions(M, a, {1, 2}, 'Test' = [[1, 2], [2]]);
printf("Result: %a\n", result3);

printf("TEST 4: From level 2 onwards\n");
result4 := FindPositions(M, a, {2, infinity}, 'Test' = [[1, 2], [3, 1, 1, 2], [4, 1]]);
printf("Result: %a\n\n", result4);

printf("TEST 5: First 2 results\n");
result5 := FindPositions(M, a, infinity, 2, 'Test' = [[1, 2], [2]]);
printf("Result: %a\n", result5);

@Jean-Michel 
Need to clarify which test examples for Mathematica are available for the Position function?
Maybe the desired functionality can be done in Maple ?

@Jean-Michel 

The Position function works even more extensively in Mathematica.

It depends on what you want to calculate.

Try to make this possible in Maple.

@Jean-Michel 
 

Position := proc(expr, target, path := [])
    local i, res := []:

    if expr = target then
        return [path];
    elif type(expr, list) then
        for i to nops(expr) do
            res := [op(res), 
                    op(Position(expr[i], target, [op(path), i]))];
        od;
    elif type(expr, `+`) then
        # Voor sommen
        for i to nops(expr) do
            if type(op(i, expr), `*`) then
                # Voor producttermen in een som: match het hele product
                if has(op(i, expr), target) then
                    res := [op(res), [op(path), i]];
                end if;
            else
                # Voor andere termen: ga recursief
                res := [op(res),
                        op(Position(op(i, expr), target, [op(path), i]))];
            end if;
        od;
    elif type(expr, `*`) then
        # Voor producten buiten een som: ga recursief
        for i to nops(expr) do
            res := [op(res),
                    op(Position(op(i, expr), target, [op(path), i]))];
        od;
    fi;

    return res;
end proc:


# Test
M := [[1, a], a, [[3 + a]], 2*a - 1]:
Position(M, a);

matrices_of_matrices_mprimes_20-1-2026.mw

nm 11983 
Isn't it fantastic that Maple gives a dot for multiplication in expressions !

It clearly shows when there is multiplication and can be useful for some users, I think.

@sand15 
"The mode  can be quite difficult to catch given the wide variety of pdf a mixture can have.
So this is a quite simple, likely not optimal, procedure to do this."

Can this procedure : FindGlobalMode_FP_Visual_RV_simple handle all mixtures ?

 

restart;
with(plots):
with(Statistics):

FindGlobalMode_FP_Visual_RV_simple := proc(
    GRVs::list,           # Lijst van RandomVariable objecten
    pi_weights::list,     # Mengselgewichten
    N::posint := 10^4,
    tol::numeric := 1e-10,
    maxit::posint := 200
)
  local K, j;
  local starts, z, znew, i, k;
  local modes, vals, xmode;
  local f, Gmap, pi, mu_list, sigma_list;
  local sample_list, rnd_val, cum_prob, component_chosen;
  local xmin, xmax, max_std, overall_mean;
  local hist_plot, pdf_plot, mode_line, mode_point;
  local u1, u2, s, z_box;

  K := nops(GRVs);

  if nops(pi_weights) <> K then
    error "GRVs and pi_weights must have the same length";
  end if;

  # Gebruik Mean en StandardDeviation functies
  mu_list := [seq(Mean(GRVs[j]), j=1..K)];
  sigma_list := [seq(StandardDeviation(GRVs[j]), j=1..K)];  # sigma, niet sigma^2

  # Toon voor debugging
  print("Component means:", mu_list);
  print("Component standard deviations:", sigma_list);

  # Normalize weights
  pi := [seq(pi_weights[j]/add(pi_weights), j=1..K)];

  # --------------------------------------------------
  # 1. ANALYTISCHE PDF - via RandomVariable PDFs
  # --------------------------------------------------
  f := x -> add(pi[j]*PDF(GRVs[j], x), j=1..K);

  # --------------------------------------------------
  # 2. VASTE-PUNT MAP (gebruik sigma^2 = sigma_list[j]^2)
  # --------------------------------------------------
  Gmap := x ->
    add(pi[j]*mu_list[j]/(sigma_list[j]^2)
        *exp(-(x-mu_list[j])^2/(2*sigma_list[j]^2))/sqrt(2*Pi*sigma_list[j]^2),
        j=1..K)
    /
    add(pi[j]/(sigma_list[j]^2)
        *exp(-(x-mu_list[j])^2/(2*sigma_list[j]^2))/sqrt(2*Pi*sigma_list[j]^2),
        j=1..K);

  # --------------------------------------------------
  # 3. ZOEK GLOBALE MODUS
  # --------------------------------------------------
  starts := [op(mu_list), add(pi[j]*mu_list[j], j=1..K)];

  modes := [];
  vals  := [];

  for k to nops(starts) do
    z := evalf(starts[k]);

    for i to maxit do
      znew := evalf(Gmap(z));
      if abs(znew - z) < tol then
        break;
      end if;
      z := znew;
    end do;

    modes := [op(modes), z];
    vals  := [op(vals), f(z)];
  end do;

  xmode := modes[ ListTools:-Search(max(vals), vals) ];

  # --------------------------------------------------
  # 4. SAMPLING - DIRECTE BOX-MULLER METHODE
  # --------------------------------------------------
  sample_list := Vector(N, datatype=float[8]);
  
  # Initialiseer random seed
  randomize();
  
  for i from 1 to N do
    # Gebruik rand() voor uniform [0,1] om component te kiezen
    rnd_val := rand()/10^12;
    
    # Kies component
    cum_prob := 0;
    component_chosen := 1;
    for j from 1 to K do
      cum_prob := cum_prob + pi[j];
      if rnd_val <= cum_prob then
        component_chosen := j;
        break;
      end if;
    end do;
    
    # Genereer normaal verdeeld getal met Box-Muller
    s := 2;
    while s >= 1 do
      u1 := 2*rand()/10^12 - 1;
      u2 := 2*rand()/10^12 - 1;
      s := u1^2 + u2^2;
    end do;
    
    z_box := u1*sqrt(-2*ln(s)/s);  # Standaard normale variabele
    
    # Transformeer naar gekozen component
    sample_list[i] := mu_list[component_chosen] + sigma_list[component_chosen] * z_box;
  end do;

  sample_list := convert(sample_list, list);
  
  # --------------------------------------------------
  # 5. VISUALISATIE
  # --------------------------------------------------
  max_std := max(op(sigma_list));
  overall_mean := add(pi[j]*mu_list[j], j=1..K);
  
  xmin := min(overall_mean - 5*max_std, min(op(mu_list)) - 4*max_std);
  xmax := max(overall_mean + 5*max_std, max(op(mu_list)) + 4*max_std);

  hist_plot := Histogram(sample_list, color="LightGray", style=polygon);
  pdf_plot := plot(f(x), x=xmin..xmax, color=red, thickness=2);
  mode_line := plot([[xmode,0],[xmode,f(xmode)]], color=blue, linestyle=dash, thickness=2);
  mode_point := pointplot([[xmode, f(xmode)]], color=blue, symbol=solidcircle, symbolsize=15);

  print(display(hist_plot, pdf_plot, mode_line, mode_point,
    title=cat("Gaussian Mixture (K=", K, "): Global Mode = ", sprintf("%.6f", xmode)),
    labels=["x","density"],
    view=[xmin..xmax, DEFAULT]
  ));

  return xmode;

end proc:

# Goed gescheiden componenten
G13 := RandomVariable(Normal(-4, 0.7)):
G14 := RandomVariable(Normal(0, 0.9)):
G15 := RandomVariable(Normal(4, 0.6)):

weights_sep := [0.33, 0.34, 0.33]:
mode_sep := FindGlobalMode_FP_Visual_RV_simple([G13, G14, G15], weights_sep, 5000);

"Component means:", [-4, 0, 4]

 

"Component standard deviations:", [.7, .9, .6]

 

 

3.999937260

(1)

# Goed gescheiden componenten
G13 := RandomVariable(Normal(-1, 0.7)):
G14 := RandomVariable(Normal(10, 0.9)):
G15 := RandomVariable(Normal(4, 0.6)):
# Goed gescheiden componenten
G16 := RandomVariable(Normal(-5, 0.7)):
G17 := RandomVariable(Normal(1, 0.9)):
G18 := RandomVariable(Normal(15, 0.6)):
# Goed gescheiden componenten
G19 := RandomVariable(Normal(-2, 0.7)):
G20 := RandomVariable(Normal(-1, 0.9)):
G21 := RandomVariable(Normal(13, 0.6)):

weights_sep := [0.33, 0.34, 0.33, 0.35, 0.35, 0.30,0.4, 0.4, 0.4]:
mode_sep := FindGlobalMode_FP_Visual_RV_simple([G13, G14, G15, G16, G17, G18,G19, G20, G21], weights_sep, 5000);

"Component means:", [-1, 10, 4, -5, 1, 15, -2, -1, 13]

 

"Component standard deviations:", [.7, .9, .6, .7, .9, .6, .7, .9, .6]

 

 

-1.331489397

(2)
 

NULL

Download mixture_mengsel_via_randon_variabele_invoer_normaal_verdeeld_pdf_mprimes_20-1-2026.mw

1 2 3 4 5 6 7 Last Page 1 of 82