1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
/*
Copyright (C) 2022 Fredrik Johansson
This file is part of FLINT.
FLINT is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License (LGPL) as published
by the Free Software Foundation; either version 3 of the License, or
(at your option) any later version. See <https://www.gnu.org/licenses/>.
*/
#include "gr.h"
#include "gr_mat.h"
int
gr_mat_nullspace(gr_mat_t X, const gr_mat_t A, gr_ctx_t ctx)
{
slong i, j, k, m, n, rank, nullity;
slong *p;
slong *pivots;
slong *nonpivots;
gr_mat_t tmp;
int status = GR_SUCCESS;
slong sz = ctx->sizeof_elem;
gr_ptr den;
int with_den;
m = gr_mat_nrows(A, ctx);
n = gr_mat_ncols(A, ctx);
p = flint_malloc(sizeof(slong) * FLINT_MAX(m, n));
gr_mat_init(tmp, m, n, ctx);
GR_TMP_INIT(den, ctx);
with_den = gr_ctx_is_field(ctx) == T_FALSE && gr_ctx_is_integral_domain(ctx) == T_TRUE;
if (with_den)
{
status |= gr_mat_rref_den(&rank, tmp, den, A, ctx);
}
else
{
status |= gr_mat_rref(&rank, tmp, A, ctx);
}
nullity = n - rank;
if (status != GR_SUCCESS)
goto cleanup;
/* todo: have a resize function */
gr_mat_clear(X, ctx);
gr_mat_init(X, n, nullity, ctx);
if (rank == 0)
{
for (i = 0; i < nullity; i++)
status |= gr_one(GR_MAT_ENTRY(X, i, i, sz), ctx);
}
else if (nullity)
{
pivots = p; /* length = rank */
nonpivots = p + rank; /* length = nullity */
for (i = j = k = 0; i < rank; i++)
{
while (1)
{
/* Todo: this should not be T_UNKNOWN. Should we save
the pivot data in the lu algorithm? */
truth_t is_zero = gr_is_zero(GR_MAT_ENTRY(tmp, i, j, sz), ctx);
if (is_zero == T_FALSE)
{
break;
}
else if (is_zero == T_TRUE)
{
nonpivots[k] = j;
k++;
j++;
}
else
{
status = GR_UNABLE;
goto cleanup;
}
}
pivots[i] = j;
j++;
}
while (k < n - rank)
{
nonpivots[k] = j;
k++;
j++;
}
if (with_den)
{
/* if we did not keep den, equivalently den = tmp[0, pivots[0]] here */
for (i = 0; i < nullity; i++)
{
for (j = 0; j < rank; j++)
status |= gr_neg(GR_MAT_ENTRY(X, pivots[j], i, sz), GR_MAT_ENTRY(tmp, j, nonpivots[i], sz), ctx);
status |= gr_set(GR_MAT_ENTRY(X, nonpivots[i], + i, sz), den, ctx);
}
}
else
{
for (i = 0; i < nullity; i++)
{
for (j = 0; j < rank; j++)
status |= gr_neg(GR_MAT_ENTRY(X, pivots[j], i, sz), GR_MAT_ENTRY(tmp, j, nonpivots[i], sz), ctx);
status |= gr_one(GR_MAT_ENTRY(X, nonpivots[i], i, sz), ctx);
}
}
}
cleanup:
flint_free(p);
gr_mat_clear(tmp, ctx);
GR_TMP_CLEAR(den, ctx);
return status;
}