Dienstag, 4. Juni 2024
Das Kartenspiel "2 oder 4"
Ich möchte heute mein neues Kartenspiel "2 oder 4" vorstellen. Es ist auf MeinSpiel erschienen als Print-On-Demand und wird so gespielt: Auf je zwei Karten gibt es genau 2 oder 4 gemeinsame Bilder. Das Ziel des Spieles ist es schnell so viele Karten wie möglich zu gewinnen, indem man die 2 oder 4 Bilder findet und benennt. Wer das Spiel zuerst einmal selbst ausprobieren möchte und gerne bastelt, der kann hier das Spiel als pdf herunterladen und selbst drucken und ausschneiden.
Es eignet sich gut als Partyspiel oder als Familienspiel. Dass es bei 36 Karten und genau zwei Karten je genau je 2 oder genau je 4 Bilder gibt, die gemeinsam sind, liegt an der Existenz eines mathematischen Objektes.
Montag, 4. März 2024
The abc conjecture and positive definite kernel on the natural numbers with inductive Cholesky decomposition.
This is a transcription of the following MathOverflow question, found here.
One formulation of the abc-conjecture is:
\[\forall a,b \in \mathbb{N}: \frac{a+b}{\gcd(a,b)} < \operatorname{rad}\left ( \frac{ab(a+b)}{\gcd(a,b)^3}\right )^2 \]
Let us define:
\[K(a,b) := \frac{2(a+b)}{\gcd(a,b)\operatorname{rad}\left ( \frac{ab(a+b)}{\gcd(a,b)^3}\right )^2} \]
I have checked in Sagemath up to \(n=100\) that the matrix
\[(K(i,j))_{1 \le i,j \le n} \text{ is positive definite }\]
and up to \(1\le a,b \le 100\) that :
\[K(a,b)\le 1\]
In the Encyclopedia of Distances the word "similarity" is described as:
A similarity \(s:X\times X \rightarrow \mathbb{R}\) is defined in the Encyclopedia of Distances as:
Edit: I think that \(4.\) can be proved by considering that if \(K(x,y)=1\) and assuming there exists a prime \(p\) which divides \(x\) but not \(y\), leads to a contradiction.
Second edit: The abc conjecture (in the version above) would follow, if one could prove that the function \[K(a,b) := \frac{2(a+b)}{\gcd(a,b)\operatorname{rad}\left ( \frac{ab(a+b)}{\gcd(a,b)^3}\right )^2} \] is positive definite over the natural numbers.
Proof: If \(K\) is a positive definite function over the natural numbers, then by the Moore-Aronszajn theorem , there exists a Hilbert space \(H\) and a feature mapping \(\phi: \mathbb{N} \rightarrow H\) such that: \[K(a,b) = \left < \phi(a),\phi(b) \right >_{H}\] But by Cauchy-Schwarz inequality we get: \[K(a,b) = |K(a,b)| = |\left < \phi(a), \phi(b) \right >_{H}|\] \[\le |\phi(a)||\phi(b)| = \sqrt{K(a,a)K(b,b)} = \sqrt{1 \cdot 1} = 1\] But then we get by division of \(2\) and application of the last inequality: \[\frac{(a+b)}{\gcd(a,b)\operatorname{rad}\left ( \frac{ab(a+b)}{\gcd(a,b)^3}\right )^2} \le \frac{1}{2} < 1 \] hence it would follow that: \[\forall a,b \in \mathbb{N}: \frac{a+b}{\gcd(a,b)} < \operatorname{rad}\left ( \frac{ab(a+b)}{\gcd(a,b)^3}\right )^2 \] Modified question: Is there a way to speed up the computations to try and test if the Gram matrix for \(n=1,\cdots,10000 \) is positive definite? Here is my code so far, but it is rather slow:
It is based on inductive Cholesky decomposition as described below and keeps track in a dictionary if the \(\phi(n)\) or \(C_n\) have already been computed. It uses float approximation for greater speed and in the last step we check if each component of the vector \(\phi(n)\) is a real number. If it is for all \(1 \le k \le n\) then we conclude that the Gram matrix of \(n\) is positive definite. If it is not, then at least the Gram matrix for \(n\) is not positive definite:
Inductive Cholesky decomposition to find an embedding \(\phi(n)\) for each number \(n\):
Equation 1): \[\phi(n+1) = \left(\begin{array}{r} {C_{n}^{-1} v_n} \\ \sqrt{k(n+1,n+1)-{\left| {C_{n}^{-1} v_n} \right|}^{2} } \end{array}\right)\] Equation 2): \[v_n = \left(\begin{array}{r} k(1,n+1) \\ k(2,n+1) \\ \cdots\\ k(n,n+1)\\ \end{array}\right)\] Equation 3): \[C_n = \left(\begin{array}{r} \phi(1)^T \\ \phi(2)^T \\ \cdots\\ \phi(n)^T\\ \end{array}\right)\] Equation 4): \[\phi(1) := \sqrt{k(1,1)} e_1\] If we assume that the function \(k\) is positive definite, then this inductive method, should give us the vectors \(\phi(a),\phi(b)\) such that under the normal inner product we have: \[k(a,b) = \left < \phi(a), \phi(b) \right > \]. Edit (11.03.2024): This conjecture about the positive semidefiniteness of \(K\) is wrong as the determinant of \(G_{192}\) is < \(0\)
- \(s(x,y) \ge 0 \forall x,y \in X\)
- \(s(x,y) = s(y,x) \forall x,y \in X\)
- \(s(x,y) \le s(x,x) \forall x,x \in X\)
- \(s(x,y) = s(x,x) \iff x=y\)
Edit: I think that \(4.\) can be proved by considering that if \(K(x,y)=1\) and assuming there exists a prime \(p\) which divides \(x\) but not \(y\), leads to a contradiction.
Second edit: The abc conjecture (in the version above) would follow, if one could prove that the function \[K(a,b) := \frac{2(a+b)}{\gcd(a,b)\operatorname{rad}\left ( \frac{ab(a+b)}{\gcd(a,b)^3}\right )^2} \] is positive definite over the natural numbers.
Proof: If \(K\) is a positive definite function over the natural numbers, then by the Moore-Aronszajn theorem , there exists a Hilbert space \(H\) and a feature mapping \(\phi: \mathbb{N} \rightarrow H\) such that: \[K(a,b) = \left < \phi(a),\phi(b) \right >_{H}\] But by Cauchy-Schwarz inequality we get: \[K(a,b) = |K(a,b)| = |\left < \phi(a), \phi(b) \right >_{H}|\] \[\le |\phi(a)||\phi(b)| = \sqrt{K(a,a)K(b,b)} = \sqrt{1 \cdot 1} = 1\] But then we get by division of \(2\) and application of the last inequality: \[\frac{(a+b)}{\gcd(a,b)\operatorname{rad}\left ( \frac{ab(a+b)}{\gcd(a,b)^3}\right )^2} \le \frac{1}{2} < 1 \] hence it would follow that: \[\forall a,b \in \mathbb{N}: \frac{a+b}{\gcd(a,b)} < \operatorname{rad}\left ( \frac{ab(a+b)}{\gcd(a,b)^3}\right )^2 \] Modified question: Is there a way to speed up the computations to try and test if the Gram matrix for \(n=1,\cdots,10000 \) is positive definite? Here is my code so far, but it is rather slow:
# inductive cholesky decomposition
def rad(n):
return prod(prime_divisors(n))
def kk(a,b):
return (2*(a+b)*a**1*b**1/gcd(a,b))*1/rad(a*b*(a+b)/gcd(a,b)**3)**2
def notPositiveDefinite(a,b):
return rad(a*b/gcd(a,b))
#kk = notPositiveDefinite
def grammat(kk,n):
return matrix([[kk(a,b) for a in range(1,n+1)] for b in range(1,n+1)],ring=QQ)
PHI = dict([])
def phi(n,useN=False):
if n in PHI.keys():
return PHI[n]
if n==1:
if not useN:
x = vector([sqrt(kk(1,1))])
else:
x = vector([sqrt(kk(1,1)+0.0)])
PHI[n] = x
return x
else:
w = CC(n-1)**(-1)*vv(n-1)
lw = list(w)
if not useN:
lw.append(sqrt(kk(n,n)-w.norm()**2))
else:
lw.append(sqrt(kk(n,n)-w.norm().n()**2).n())
x = vector(lw)
PHI[n]= x
return x
def vv(n):
return vector([kk(i,n+1) for i in range(1,n+1)])
CCDict = dict([])
def CC(n):
if n in CCDict.keys():
return matrix(CCDict[n])
mm = []
for i in range(1,n+1):
vi = list(phi(i))
if len(vi) < n:
vi.extend((n-i)*[0])
mm.append(vi)
M= matrix(mm)
CCDict[n] = mm
return M
for n in range(1,200):
print(n,all(x in RR for x in phi(n,useN=True)))
#print(grammat(kk,n).rational_form())
```
Comment on code: It is based on inductive Cholesky decomposition as described below and keeps track in a dictionary if the \(\phi(n)\) or \(C_n\) have already been computed. It uses float approximation for greater speed and in the last step we check if each component of the vector \(\phi(n)\) is a real number. If it is for all \(1 \le k \le n\) then we conclude that the Gram matrix of \(n\) is positive definite. If it is not, then at least the Gram matrix for \(n\) is not positive definite:
Inductive Cholesky decomposition to find an embedding \(\phi(n)\) for each number \(n\):
Equation 1): \[\phi(n+1) = \left(\begin{array}{r} {C_{n}^{-1} v_n} \\ \sqrt{k(n+1,n+1)-{\left| {C_{n}^{-1} v_n} \right|}^{2} } \end{array}\right)\] Equation 2): \[v_n = \left(\begin{array}{r} k(1,n+1) \\ k(2,n+1) \\ \cdots\\ k(n,n+1)\\ \end{array}\right)\] Equation 3): \[C_n = \left(\begin{array}{r} \phi(1)^T \\ \phi(2)^T \\ \cdots\\ \phi(n)^T\\ \end{array}\right)\] Equation 4): \[\phi(1) := \sqrt{k(1,1)} e_1\] If we assume that the function \(k\) is positive definite, then this inductive method, should give us the vectors \(\phi(a),\phi(b)\) such that under the normal inner product we have: \[k(a,b) = \left < \phi(a), \phi(b) \right > \]. Edit (11.03.2024): This conjecture about the positive semidefiniteness of \(K\) is wrong as the determinant of \(G_{192}\) is < \(0\)
Samstag, 2. März 2024
Application of Ehrhart polynomials for counting of numbers and lattices for natural numbers.
This is a transcription of the MO question written here:
It is known that \(\log(p)\) is independent as a vector over the rational numbers where \(p\) is a prime.
We have \(\log(ab) = \log(a)+\log(b)\) and \(\log(n) = \sum_{p |n}v_p(n) \log(p)\).
We define \(\psi(n) := \sum_{p |n}v_p(n) e_p\) where \(e_p\) is the \(p\)-th standard basis vector of the Hilbert space of sequences.
for \(q = a/b \in \mathbb{Q}_{>0}\) we define:
\[\psi(a/b) := \psi(a/\gcd(a,b))-\psi(b/\gcd(a,b))\].
We have for \(n \in \mathbb{N}\):
\[\|\psi(n)\|^2 = \sum_{p|n} v_p(n)^2 \text{ is a natural number}\]
Furthermore the function
\[K(a,b) = \left < \psi(a),\psi(b)\right > = \sum_{p|\gcd(a,b)} v_p(a)v_p(b)\]
is a positive definite kernel on the natural numbers.
Let us define the \(\infty\)-dimensional lattice \(\Gamma\) as:
\(\Gamma:= \{\psi(q)| q \in \mathbb{Q}_{>0}, \|\psi(q)\|^2 \equiv 0 \mod(2)\}\)
and let us also define:
\[\eta(n) := (-1)^{\|\psi(n)\|^2}= \prod_{p|n}(-1)^{v_p(n)^2}\]
For \(\psi(a),\psi(b) \in \Gamma\) we have:
\[\|\psi(ab)\|^2 = \|\psi(a)+\psi(b)\|^2 = \|\psi(a)\|^2+\|\psi(b)\|^2+2K(a,b) \equiv 0+0+0 \equiv 0 \mod(2)\]
Therefore \(\psi(a)+\psi(b) \in \Gamma\) and \(\psi(1) \in \Gamma\).
The lattice shares some properties with the Leech-lattice and the E8 lattice:
1. It is unimodular in the sense that: For a finite set of primes, the gram matrix \((K(p,q))_{p,q \text{ is prime}}\) has \(\det=1\).
2. It is even: \(\forall x \in \Gamma: |x|^2 \equiv 0 \mod(2)\)
3. For all nonzero vectors in the lattice the squared norm is at least \(2\).
My questions are these:
1) Probably an easy question:
\[\eta(mn) = \eta(m) \eta(n) \forall m,n\in \mathbb{N}\]
2) Does it satisfy a Riemann-Hypothesis type of random variable equality:
\[\forall \epsilon > 0 : \lim_{N\rightarrow \infty} \frac{1}{N^{1/2+\epsilon}}\sum_{n=1}^N \eta(n) = 0\]
3) Is there a relationship to the Riemann Hypothesis and this lattice?
Here is some Sagemath code for experiments.
And here is some picture concerning the 2. question:
**Edit**:
Let \(\lambda(n)=(-1)^{\Omega(n)}\) be the Liouville function.
Then because \(v_p(n)^2\equiv v_p(n) \mod(2)\), we have indeed:
\[\eta(n)= \lambda(n)\]
This answers the first question since it is known that \(\lambda\) is multiplicative.
This also answers the second and third question.
Modified question: Is this lattice known in literature?
Thanks for your help.
-------------------------------------------------------------------------------------------------
A maybe useful point of view, is to use the Ehrhart polynomial of a polytope, namely the simplex, to count the numbers as points in a simplex:
Let \(Q_N:=\) Polytope of \((\{\psi(p)|1\le p \le N, p \text{ prime }\})\)
Then the polytope generated by the primes is the simplex, and it is known ( "Computing the continuous discretely" Matthias Beck, Sinai Robins, Second edition, p.31 ff) that the Ehrhart polynomial is given by:
\[L(Q_N,t) = \operatorname{binomial}(d+t,d)\]
where \(d= \pi(N)\) is the dimension of the simplex, and it is equal to the number of primes \(\le N\), which is denoted by \(\pi(N)\). Let \(\hat{\pi}(n):=\{p \text{ prime}: p|n \}\) and let \(p_n:=n\)-th prime.
Since \(L(Q_N,t)\) counts the points \(\psi(n)=(x_1,\cdots,x_d)\) in the dilated polytope \(t Q_N\) and those points have coordinates \(\ge 0\) with \(x_1+\cdots+x_d \le t\), we conclude that, by observing that the sum of the coordinates correspond to \(\Omega(n) := \sum_{p|n} v_p(n)\):
\[L(Q_N,t) = |\{\psi(n) : \Omega(n) \le t , \hat{\pi}(n) \subset \hat{\pi}(N!), 1 \le n \le p_{\pi(N)}^t\}|\]
The condition \(\hat{\pi}(n) \subset \hat{\pi}(N!)\) is for making sure we look at those numbers which have only prime divisors \(\le N\).
We also observe that:
\[L(Q_N,t)-L(Q_N,t-1) = |\{ n : 1 \le n \le p_d^t, \Omega(n)=t, \hat{\pi}(n) \subset \hat{\pi}(N!) \}| = |A_{N,t}|\]
where I have defined:
\[A_{N,t} = \{ n : 1 \le n \le p_d^t, \Omega(n)=t, \hat{\pi}(n) \subset \hat{\pi}(N!) \}\]
We can now define and try to evaluate the following sum:
\[F(N,t):= \sum_{k=0}^t \sum_{n \in A_{N,k}} \lambda(n)\]
\[=\sum_{k=0}^t (-1)^k ( L(Q_N,k)-L(Q_N,k-1) )\]
\[=\sum_{k=0}^t (-1)^k ( \operatorname{binomial}(d+k,d)-\operatorname{binomial}(d+k-1,d) )\]
which according to Wolfram Alpha is equal to:
\[=((-1)^t \operatorname{binomial}(d+t+1,d) F_{2,
1}(1,d+t+2;t+2;-1)+2^{-d-1})-2^{-d-1}(2^{d+1}(-1)^t \operatorname{binomial}(d+t,d)F_{2,1}(1,d+t+1;t+1;-1))\]
\[=((-1)^t \operatorname{binomial}(\pi(N)+t+1,\pi(N)) F_{2,1}(1,\pi(N)+t+2;t+2;-1)+2^{-\pi(N)-1})-2^{-\pi(N)-1}(2^{\pi(N)+1}(-1)^t \operatorname{binomial}(\pi(N)+t,\pi(N))F_{2,1}(1,\pi(N)+t+1;t+1;-1))\]
where \(F_{2,1}(a,b;c;z)\) is the hypergeometric function.
I must admit that the formula is not really "nice" but I think it should be useful, because using the RHS of the last equality with \(d\) could maybe be extended to other values for \(d,t\) other than the natural numbers.
I can also not see, how to relate the sum \(F(N,t)\) to the Liouville sum:
\[\sum_{n=1}^N \lambda(n)\]
The naive idea is that in the limit \(N\rightarrow \infty, t \rightarrow \infty\), the two sets:
\[\mathbb{N}:= \lim_{N\rightarrow \infty}\{1,\cdots,N\} \text{ and } \lim_{N,t\rightarrow \infty} A_{N,t} \]
should be intuitively equal.
There is also an equivalent formulation of the Riemann Hypothesis with the points on a different polytope, but while it uses the Ehrhardt polynomials, which in this case are very complicated at \(t=1\) I can not see how to derive an analytic formula in this case.
Here you can find some sanity check in SageMath.
Let \(B_{N,t} = \{n : \Omega(n) \le t , \hat{\pi}(n) \subset \hat{\pi}(N!), 1 \le n \le p_{\pi(N)}^t\}\), so that
\[\operatorname{binomial}(d+t,d) = L(Q_N,t) = |B_{N,t}|\]
The arguments above show that:
\[\sum_{n \in B_{N,t}} \lambda(n) = F(N,t) = \]
\[=((-1)^t \operatorname{binomial}(d+t+1,d) F_{2,1}(1,d+t+2;t+2;-1)+2^{-d-1})-2^{-d-1}(2^{d+1}(-1)^t \operatorname{binomial}(d+t,d)F_{2,1}(1,d+t+1;t+1;-1))\]
hence dividing by the number of points under which the sum runs, we get:
\[\frac{1}{|B_{N,t}|} \sum_{n \in B_{N,t}} \lambda(n) = \frac{1}{|B_{N,t}|} F(N,t) = \]
\[=(-1)^t \frac{d}{t+1}F_{2,1}(1,d+t+2;t+2;-1)+(-1)^t F_{2,1}(1,d+t+2;t+2;-1)+\frac{1}{2^{d+1} \operatorname{binomial}(d+t,d)}+(-1)^{t+1}F_{2,1}(1,d+t+1;t+1;-1)\]
where \(d:=\pi(N)\).
Notice the similarity to the prime number theorem:
We have in both cases sets \(C_N\) such that:
\[\lim_{N\rightarrow \infty} \frac{1}{|C_N|} \sum_{n \in C_N} \lambda(n) = 0\]
The case \(C_N := \{1,\cdots,N\}\) corresponds by Landau equivalently to the prime number theorem.
We observe that:
\[\lim_{N \rightarrow \infty} B_{N,t} = \{n \in \mathbb{N} | \Omega(n) \le t \} =: B_{\infty,t}\]
and that
\[\lim_{t \rightarrow \infty}(\lim_{N\rightarrow \infty} B_{N,t} ) = \lim_{t \rightarrow \infty} B_{\infty,t} = \lim_{t
\rightarrow \infty} \{n \in \mathbb{N} | \Omega(n) \le t \} = \mathbb{N}\]
Similarly:
\[\lim_{N \rightarrow \infty}(\lim_{t\rightarrow \infty} B_{N,t} ) = \lim_{N \rightarrow \infty} B_{N,\infty} = \lim_{N \rightarrow \infty} \{n \in \mathbb{N} | \hat{\pi}(n) \subset \hat{\pi}(N!)\} = \mathbb{N}\]
Hence we have:
\[\lim_{t \rightarrow \infty, N \rightarrow \infty} B_{N,t} = \mathbb{N}\]
(Here we have used that there are infinitely many primes.)
Now let us put \(C_N := B_{N,\pi(N)}\).
Then one empirical observation, which I was not able to prove directly, is:
\[\lim_{N \rightarrow \infty} \frac{1}{|C_N|} \sum_{n \in C_N} \lambda(n) =^? 0\]
which reminds a little bit on the prime number theorem where \(C_N:=\{1,\cdots,N\}\).
Sonntag, 17. Dezember 2023
A class of number theoretic finite semirings
Abstract: This work presents a novel structure of finite semirings constructed from factorization trees. We first establish the foundational elements of our theory by defining the largest and smallest prime divisors of a natural number. Utilizing these divisors, we construct factorization trees that inherently determine the lexicographic ordering of the factorizations. These trees enable us to define a projection function, which reinterprets factorization trees as decision trees for the projection of larger numbers.
We introduce two recursive definitions for the projection function, $\pi_n(N)$, one based on the decision tree interpretation and another on divisors and lexicographic sorting. Tables of values for $\pi_i(N)$ provide insight into the behavior of these functions. Moreover, we identify the properties of $\pi_n(N)$, which are pivotal to the semiring operations defined on the set $[n]$.
The addition and multiplication operations, denoted as $\oplus$ and $\otimes$ respectively, are defined through the iteration of the successor function. This leads to the establishment of $([n], \oplus, \otimes)$ as an abelian semiring. We also propose a notation to express congruence under projection and demonstrate the properties that validate the semiring definition.
The abstract concludes with conjectures to simplify the computation of $\oplus$ and $\otimes$, supported by visual representations of addition and multiplication tables and successor graphs for various $n$ values. These conjectures, if proven, can significantly enhance computational efficiency and confirm the structure as an abelian semiring.
Download-Link (pdf).
Sonntag, 26. November 2023
A note in inverse Galois theory.
Abstract:
The note explores connections between inverse Galois theory and Hilbert irreducibility, presenting results in the form of theorems and lemmas. The main focus is on establishing conditions under which a finite group can be realized as a Galois group over the rational numbers. The note introduces a corresponding polynomial associated with a finite group and explores its irreducibility over specific varieties. The main results include Theorem 1, which establishes conditions for a group to be a Galois group, and Theorem 2, which demonstrates the equivalence between the applicability of Hilbert irreducibility to the corresponding polynomial and the realizability of every finite group as a Galois group over the rational numbers. The note concludes with corollaries and lemmas supporting the main theorems. It can be downloaded as pdf from here.
The note explores connections between inverse Galois theory and Hilbert irreducibility, presenting results in the form of theorems and lemmas. The main focus is on establishing conditions under which a finite group can be realized as a Galois group over the rational numbers. The note introduces a corresponding polynomial associated with a finite group and explores its irreducibility over specific varieties. The main results include Theorem 1, which establishes conditions for a group to be a Galois group, and Theorem 2, which demonstrates the equivalence between the applicability of Hilbert irreducibility to the corresponding polynomial and the realizability of every finite group as a Galois group over the rational numbers. The note concludes with corollaries and lemmas supporting the main theorems. It can be downloaded as pdf from here.
Freitag, 2. November 2018
A marketplace for machine learning models? onnx, pmml or pfa?
A simple search for "marketplace for machine learning models" reveals that a company called Algorithmia has built such a thing and has over 5000 models in the marketplace, most of which are machine learning related. However, if one wants to use/buy a model, one has to trust a third party, namely Algorithmia, to run that model. Also, the cost to use a model is based on the number of request. Hence the buyer does not own the model. There is another option, which does not exist yet to my knowledge, namely to directly sell the machine learning model to the buyer. This option is proposed here: https://arxiv.org/pdf/1805.11450.pdf. Although the paper is very technical, the main idea is to directly sell the machine learning model. This decouples the process of buying and running a model. Since models are trained on data and later scored on new data, this means, that the seller of the model and the buyer of the model, must have access to some similar dataset. This could be achieved by using open data. This is also the reason, why most of the models on Algorithmia are based on commond data, such as text and images. The data scientist trains his model on open data to solve a specific problem and then uploads his model to a marketplace. The buyer, could then upload open train data to the marketplace and let the model score the data to see how well the model performs. So he does not have to trust the seller of the model in terms of model accurracy. Based on the performance of different models, the buyer of the model, can choose the model, with the best accurracy and then the buyer can decide where to run the model, either on the cloud or on premise. This raises the question: What actually is a machine learning model? You could say, that a machine learning model is a specification of how to produce an output given some input. The next question is, how to transport a model from seller to buyer? This could be achieved using a model-format such as ONNX, PMML or PFA (portable format for analytics). The next question is , which of these model-format will be used? This is a wrong question to be posed. Why? Because as there are many document formats ( doc, docx, pdf, odf etc.) there can be many model-based formats. The analogy to document formats makes one thing clear: There are producers of documents and consumer of documents. The producers can nowadays choose from a set of marketplaces [just google: marketplace sell pdf], where to sell the document. Similarily the buyer can choose where to buy. This is only possible by decoupling the process of creating a document and viewing the document. Thus, it should be possible to do the same with machine learning models, using model-formats. A company comes to mind, where already a lot of data scientists, compete for producing the best model: Kaggle. Thus Kaggle or similar websites, might be candidates for offering such a marketplace for "opend-data-ml-models". The only thing they have to do, is offering a service for data scientists to export their "kernels" to a model-format such as ONNX, PMML or PFA and then let companys find the best model which solves their problem.
Edit: I wrote a request to Kaggle, but did not get a response, so I decided to start an experiment, to see how the idea eveolves:
mlmarketplace, buy and sell onnx, pmml, pfa
What is your opinion on this topic? Comments are welcome!
Please share this article if you like the idea.
Dienstag, 24. Januar 2017
A note in Galois Theory
Theorem 1:
Let $$\mathbb{G} = \{ \sigma_1,\cdots,\sigma_n\}$$ be a finite group, $$x_1,\cdots,x_n$$ be indeterminates
and let $$\rho$$ be the regular representation of $$\mathbb{G}$$. Let $$x = (x_1,\cdots,x_n)^T$$ and $$G = (\rho(\sigma_1)x,\cdots,\rho(\sigma_n)x)$$ , $$A' = diag(x_1,\cdots,x_n)$$.
Set $$A=GA'G^{-1}$$. Suppose there exists $$\alpha:=(\alpha_1,\cdots,\alpha_n) \in \mathbb{C}^n$$ such that:
1) $$det(G(\alpha)) \neq 0$$
2) $$A = A(\alpha)$$ has rational coefficients
3) the characteristic polynomial $$\chi_A(t)$$ is irreducible over $$\mathbb{Q}$$.
Then $$Gal(\chi_A(t)/\mathbb{Q}) = \mathbb{G}$$.
Proof:
On the one hand we have
\[ GA' = AG = GA' = (x_1\rho(\sigma_1)x,\cdots,x_n\rho(\sigma_n)x) \]
On the other hand we have
\[ GA' = AG = A (\rho(\sigma_1)x,\cdots,\rho(\sigma_n)x) = (A\rho(\sigma_1)x,\cdots,A\rho(\sigma_n)x) \]
and it follows that
\[
(A\rho(\sigma_1)x,\cdots,A\rho(\sigma_n)x) = GA' = (x_1\rho(\sigma_1)x,\cdots,x_n\rho(\sigma_n)x)
\]
and so we get
\begin{equation}\label{eq:1}
A\rho(\sigma_i)x = x_i \rho(\sigma_i)x \text{ for } i=1,\cdots,n
\end{equation}
Let $$K:=\mathbb{Q}(\alpha_1,\cdots,\alpha_n)$$. From $$A\rho(\sigma_i) \alpha = \alpha_i \rho(\sigma_i)\alpha$$ follows
for $$i=1$$, $$\rho(\sigma_1) = 1$$ that $$A\alpha = \alpha_1 \alpha$$. Application of $$\tau \in Gal(K/\mathbb{Q})$$
at the coefficients of the last equation gives us with $$\tau(A) = A$$ (since $$A$$ has rational coefficients)
that
\begin{equation}\label{eq:2}
A\tau(\alpha) = \tau(\alpha_1)\tau(\alpha) = \alpha_{\tau} \tau(\alpha)
\end{equation}
where we have set $$\alpha_{\tau} = \tau(\alpha_1)$$. This means that $$\tau(\alpha)$$ is an eigenvector of $$A$$ to the
eigenvalue $$\alpha_{\tau}$$. But because of equation $$(1)$$ we have:
\begin{equation}\label{eq:3}
A\rho(\sigma_{\tau}) \alpha = \alpha_{\tau} \rho(\sigma_{\tau}) \alpha
\end{equation}
Since the eigenvectors $$\rho(\sigma_1)\alpha,\cdots,\rho(\sigma_n)\alpha$$ of $$A$$ build a basis of $$K^n$$, it means
that every eigenspace has dimension $$1$$. Especially there exists $$a_{\tau} \in K$$ such that
\begin{equation}\label{eq:4}
\tau(\alpha) = a_{\tau} \rho(\sigma_{\tau}) \alpha
\end{equation}
If we build the polynomials with roots from the coefficients of the left and right side of $$(4)$$, then they must
be because of $$(4)$$ be equal:
\begin{equation}\label{eq:5}
\chi_A(t) = \prod_{i=1}^n (t -\alpha_i) =^{(4)} \prod_{j=1}^n (t - a_{\tau} \alpha_j)
\end{equation}
This means that the coefficients of both polynomials must be equal, especially we get
\begin{equation}\label{eq:6}
\sum_{i=1}^n \alpha_i = a_{\tau} \sum_{i=1}^n \alpha_i
\end{equation}
By a theorem of Frobenius concerning the factorization of the group determinant, we have
\begin{equation}\label{eq:7}
det( G(x_1,\cdots,x_n)) = (x_1+\cdots+x_n) p(x_1,\cdots,x_n)
\end{equation}
for some polynomial $$p$$. From $$(7)$$ follows by assumption
\[
0 \neq det(G(\alpha_1,\cdots,\alpha_n)) = (\alpha_1+\cdots+\alpha_n) p(\alpha_1,\cdots,\alpha_n)
\]
which means that $$0 \neq \alpha_1+\cdots+\alpha_n$$ and because of $$(6)$$ we get
\begin{equation}\label{eq:8}
a_{\tau} = 1
\end{equation}
From $$(4)$$ and $$(8)$$ it follows that
\begin{equation}\label{eq:9}
P_{\tau} \alpha = \tau(\alpha) = \rho(\sigma_{\tau}) \alpha
\end{equation}
where $$P_{\tau}$$ is the permutation matrix which corresponds to $$\tau$$. Since
\[
\chi_A(t) = \prod_{i=1}^n t-\alpha_i
\]
is separable, it follows that $$\alpha_k \neq \alpha_l$$ for $$k \neq l$$.
This means that the two permutation matrices $$P_{\tau}$$ and $$\rho(\sigma_{\tau})$$ from $$(9)$$ must be equal,
that is
\begin{equation}\label{eq:10}
P_{\tau} = \rho(\sigma_{\tau})
\end{equation}
From this we get a mapping:
\[
\phi: Gal(K/\mathbb{Q}) \rightarrow \mathbb{G}, \tau \mapsto \sigma_{\tau}
\]
$$\phi$$ is injective:
Let $$\sigma_{\tau} = \phi(\tau) = \phi(\tau') = \sigma_{\tau'}$$. Then we get
\[
P_{\tau} =^{(10)} \rho(\sigma_{\tau}) = \rho(\sigma_{\tau'}) = ^{(10)} P_{\tau'}
\]
and since the regular representation $$P$$ is faithful, it follows that $$\tau = \tau'$$.
$$\phi$$ is surjective:
Let $$m = |Gal(K/\mathbb{Q})|$$, $$n=|\mathbb{G}|=deg(\chi_A(t))$$.
Since $$\chi_A(t)$$ is irreducible, $$deg(\chi_A(t)) = n$$ is a divisor of $$m = |Gal(K/\mathbb{Q})|$$ and
it follows that $$n \le m$$. Since $$\phi$$ is injective it follows that $$m \le n$$, which means that $$m=n$$.
Since the mapping $$\phi$$ is injective on two finite sets of equal size, this means that $$\phi$$ must also
be surjective.
$$\phi$$ is an antihomomorphism of groups:
\[ \tau(\alpha) = \rho(\sigma_m)\alpha \rightarrow \phi(\tau) = \sigma_m\]
\[ \tau'(\alpha) = \rho(\sigma_k)\alpha \rightarrow \phi(\tau') = \sigma_k\]
\[ (\tau \tau')(\alpha) = \rho(\sigma_l)\alpha \rightarrow \phi(\tau \tau') = \sigma_l\]
From this it follows that:
\[
\rho(\sigma_l)\alpha = (\tau \tau')(\alpha) = \tau(\tau'(\alpha)) = \tau(\rho(\sigma_k) \alpha) = \rho(\sigma_k) \tau(\alpha) = \rho(\sigma_k) \rho(\sigma_m)\alpha
\]
Since $$\alpha_i$$ are separable, it follows that the permutation matrices $$\rho(\sigma_l)$$ and $$\rho(\sigma_k \sigma_m)$$ must be equal:
\[
\rho(\sigma_l) = \rho(\sigma_k \sigma_m)
\]
and from this, since the regular representation is faithful, it follows that $$\sigma_l = \sigma_k \sigma_m$$.
From this we get:
\[
\phi(\tau \tau') = \sigma_l = \sigma_k \sigma_m = \phi(\tau') \phi(\tau)
\]
Since for two finite groups which are antiisomorph it follows that they are isomorph (if $$\phi(xy)= \phi(y)\phi(x)$$ is an antihomomorphism, then $$\Phi(x):=\phi(x)^{-1}$$ is a homomorphism),
we conclude that
\[
Gal(K/\mathbb{Q}) = \mathbb{G}
\]
Definition:
Let $$\mathbb{G}$$ be a finite group with $$n$$ elements. Let $$\mathbb{Q}[x_1,\cdots,x_n]^{\mathbb{G}} = \mathbb{Q}[g_1,\cdots,g_m]$$. Then there exist polynomials $$s_j \in \mathbb{Q}[y_1,\cdots,y_m]$$ for $$j=1,\cdots,n$$ such that
$$e_j(x_1,\cdots,x_n) = s_j(g_1(x_1,\cdots,x_n), \cdots, g_m(x_1,\cdots,x_n))$$ for $$j=1,\cdots,n$$ where $$e_j$$ is the $$j$$-elementary symmetric polynomial in $$x_k$$. Consider the polynomial
$$p(t,y_1,\cdots,y_m) = t^n - s_1(y_1,\cdots,y_m) t^{n-1}+\cdots+(-1)^n s_n(y_1,\cdots,y_m)$$ which is a polynomial in $$\mathbb{Q}[t,y_1,\cdots,y_m]$$. We call $$p$$ the corresponding polynomial of the group $$\mathbb{G}$$ to the invariants
$$g_1,\cdots,g_m$$. Let $$I=\{h \in \mathbb{Q}[y_1,\cdots,y_m] | h(g_1,\cdots,g_m) = 0 \}$$. Define the variety $$V_{\mathbb{G}} = \{ a \in \mathbb{Q}^m | h(a) = 0 \forall h \in I \}$$. We say that a polynomial is Hilbert irreducible over some variety,
if it is irreducible and there exists a point in the variety such that the polynomial remains irreducible after specializing to the point of the variety and that other polynomials are not zero on this point.
Lemma 1:
The corresponding polynomial is irreducible in $$\mathbb{Q}[t,y_1,\cdots,y_m]$$.
Proof:
If the polynomial factored in a non-trivial way, then because of the $$t^n$$ term the factors must have degree less than $$n$$ in $$t$$ (consider the factorization in $$R=\mathbb{Q}(y_1,y_2,\ldots,y_n)[t]$$; note also that we can assume that the factors over $$R$$ are monic polynomials in $$t$$). Now specialise via $$y_i\mapsto g_i$$ and we get a non-trivial factorization of the specialised polynomial in $$\mathbb{Q}[g_1,\ldots,g_m][t]$$ and hence in $$\mathbb{Q}[x_1,\ldots,x_n][t]$$ and so in $$\mathbb{Q}(x_1,\ldots,x_n)[t]$$. But we know the complete factorization in this ring, it's just $$\prod(t-x_i)$$, so our given factorization must specialise into factors of the form $$\prod_{i\in I}(t-x_i)$$ for some subsets $$I$$ of $$\{1,2,\ldots,n\}$$ (with each $$I$$ not empty or the whole thing), and the constant term of each factor must be in $$\mathbb{Q}[g_1,\ldots,g_m]$$ and hence $$G$$-invariant. This is a contradiction.
Lemma 2:
Let $$f_1,\cdots,f_r \in \mathbb{Q}(x_1,\cdots,x_n)^{\mathbb{G}}$$ and suppose that the corresponding polynomial of $$\mathbb{G}$$ is Hilbert irreducible over the variety $$V_G$$.
Then there exists $$\alpha = (\alpha_1,\cdots,\alpha_n) \in \mathbb{C}^n$$ such that:
1) $$f_1(\alpha),\cdots,f_r(\alpha)$$ are rational numbers.
2) $$\prod_{i=1}^n t - \alpha_i$$ is irreducible in $$\mathbb{Q}[t]$$.
Proof:
We can write
\[
f_i = \frac{P_i(g_1,\cdots,g_m)}{Q_i(g_1,\cdots,g_m)} \text{ for } P_i,Q_i \in \mathbb{Q}[y_1,\cdots,y_m]
\]
The corresponding polynomial $$p(t,y_1,\cdots,y_m)$$ is irreducible in $$\mathbb{Q}[t,y_1,\cdots,y_m]$$ by Lemma 1. By assumption, we can find $$(a_1,\cdots,a_m)$$ in $$V_{\mathbb{G}}$$ such that:
1) $$p(t,a_1,\cdots,a_m)$$ is irreducible in $$\mathbb{Q}[t]$$.
2) $$Q_i(a_1,\cdots,a_m) \neq 0$$ for $$i=1,\cdots,r$$.
By application of the Hilbert Nullstellensatz we can find $$\alpha =( \alpha_1,\cdots,\alpha_n) \in \mathbb{C}^n$$ such that $$g_i(\alpha) = a_i$$ for $$i=1,\cdots,m$$.
Then
\[
e_j(\alpha) = s_j(g_1(\alpha),\cdots,g_m(\alpha)) = s_j(a_1,\cdots, a_m)
\]
and the polynomial $$p(t,a_1,\cdots,a_m)$$ factors over $$\mathbb{C}$$ as
$$p(t,a_1,\cdots,a_m) = \prod_{i=1}^n t - \alpha_i $$.
Then we get
\[
f_i(\alpha) = \frac{P_i(g_1(\alpha),\cdots,g_m(\alpha))}{Q_i(g_1(\alpha),\cdots,g_m(\alpha))} = \frac{P_i(a_1,\cdots,a_m)}{Q_i(a_1,\cdots,a_m)}
\]
is a rational number, which was to be shown.
Lemma 3:
Let the notation be as in Theorem 1. Then the entries $$a_{ij}$$ of the matrix $$A$$ are elements of $$\mathbb{Q}(x_1,\cdots,x_n)^{\mathbb{G}}$$.
Proof:
We have $$A(x) = G(x) A'(x) G(x)^{-1}$$ and want to show that $$A(\rho(\sigma)x) = A(x)$$ for all $$\sigma \in \mathbb{G}$$.
For this, it is sufficient to show that
\[
A'(\rho(\sigma)x) = \rho(\sigma)A'(x)\rho(\sigma)^{-1}
\]
and
\[
G(\rho(\sigma)x) = G(x) \rho(\sigma)^{-1}
\]
as it follows that
\[
A(\rho(\sigma) x) = G(\rho(\sigma)x) A'(\rho(\sigma) x ) G(\rho(\sigma) x) ^{-1}
\]
\[
= G(x) \rho(\sigma)^{-1} \rho(\sigma) A'(x) \rho(\sigma)^{-1} \rho(\sigma) G(x)^{-1}
\]
\[
= G(x) A'(x) G(x)^{-1} = A(x)
\]
Corollary 1:
Let $$\mathbb{G}$$ be a finite group such that the correspoding polynomial is Hilbert irreducible over $$V_{\mathbb{G}}$$.
Then $$\mathbb{G}$$ is realizable over $$\mathbb{Q}$$ as a Galois group.
Proof:
Consider the regular representation of $$\mathbb{G}$$ and let $$A = (a_{ij})$$ be defined as in Theorem 1.
Then by Lemma 3 we have $$a_{ij} \in \mathbb{Q}(x_1,\cdots,x_n)^{\mathbb{G}}$$. Hence
by Lemma 2 there exists $$\alpha \in \mathbb{C}^n$$ such that
1) $$a_{ij}(\alpha)$$ are rational numbers.
2) The characteristic polynomial $$\chi_A(t)=\prod_{i=1}^n t-\alpha_i$$ is irreducible in $$\mathbb{Q}[t]$$.
Since $$a_{ij}(\alpha)$$ are rational numbers, the matrix $$A(\alpha) = G(\alpha) A'(\alpha) G(\alpha)^{-1}$$
is defined for $$\alpha$$, hence $$det(G(\alpha)) \neq 0$$.
By Theorem 1 therefore it follows that $$Gal(\chi_A(t) / \mathbb{Q}) = \mathbb{G}$$.
Theorem 2:
The following are equivalent:
1) Hilbert Irreducibility can be applied to the corresponding polynomial $$p(t,y_1,\cdots,y_m)$$ over the variety $$V_\mathbb{G}$$
2) Every finite group $$\mathbb{G}$$ is Galois over $$\mathbb{Q}$$.
Proof:
1) $$\rightarrow$$ 2): Corollary 1.
2) $$\rightarrow$$ 1)
Let $$\mathbb{G} = Gal(K/\mathbb{Q}) = \{ \sigma_1,\cdots,\sigma_n\}$$ be a Galois group. By the normal
basis theorem there exists a $$\theta \in K$$ such that $$\sigma_1(\theta),\cdots,\sigma_n(\theta)$$ build a
basis of $$K$$ over $$\mathbb{Q}$$. Let $$\mathbb{Q}[x_1,\cdots,x_n]^\mathbb{G} = \mathbb{Q}[g_1,\cdots,g_m]$$ where
$$\mathbb{G}$$ acts through the regular representation. Let $$I=\{h \in \mathbb{Q}[y_1,\cdots,y_m] | h(g_1,\cdots,g_m)=0\}$$
and $$V_\mathbb{G} = \{ a \in \mathbb{Q}^m | h(a) = 0 \forall h \in I \}$$.
Let now $$Q_1,\cdots,Q_r \in \mathbb{Q}[y_1,\cdots,y_m]$$ be given, such that $$Q_i \notin I$$ for $$i=1,\cdots,r$$. Let $$Q:=Q_1\cdots Q_r$$.
Since $$I$$ is a prime ideal and $$Q_i \notin I$$, we must have $$Q \notin I$$, which means that there exists $$b \in \mathbb{Q}^n$$ such that
\[ Q(g_1(b),\cdots,g_m(b)) \neq 0 \]
that is $$\hat{f}(x_1,\cdots,x_n) = Q(g_1(x_1,\cdots,x_n),\cdots,g_m(x_1,\cdots,x_n))$$ is a reduced polynomial ( since $$\mathbb{Q}$$ has infinite elements)
(see Algebra, Lang, p. 177, p. 312).
Since the $$\sigma_i$$ by Artin (p. 311, Th. 12.2 Algebra, Lang) are algebraically independent and $$\hat{f}$$ is reduced,
there exists $$\alpha \in K$$, such that
\[
0 \neq Q(g_1(\sigma_1(\alpha),\cdots,\sigma_n(\alpha)),\cdots,g_m(\sigma_1(\alpha),\cdots,\sigma_n(\alpha)))
\]
Let $$\alpha = \sum_{i=1}^n{\alpha_i \sigma_i(\theta)}$$ with $$\alpha_i \in \mathbb{Q}$$
Then we have for $$i=1,\cdots,m$$ that $$g_i(\sigma_1(\alpha),\cdots,\sigma_n(\alpha)) = p_i(\alpha_1,\cdots,\alpha_n)$$ is a rational number,
where $$p_i$$ is some polynomial in $$\mathbb{Q}[x_1,\cdots,x_n]$$.
But then also
\[ 0 \neq Q(g_1(\sigma_1(\alpha),\cdots,\sigma_n(\alpha)),\cdots,g_m(\sigma_1(\alpha),\cdots,\sigma_n(\alpha)))
\]
\[
= Q(p_1(\alpha_1,\cdots,\alpha_n),\cdots, p_m(\alpha_1,\cdots,\alpha_n))
\]
\[
= q(\alpha_1,\cdots,\alpha_n)
\]
for some polynomial $$q \in \mathbb{Q}[x_1,\cdots,x_n]$$. We can choose the $$\alpha_i$$ such that $$\alpha_i \neq \alpha_j$$ for $$i \neq j$$,
otherwise replace $$\hat{\alpha}_j = \alpha_i + u$$ for some rational number $$u \neq 0$$ and we get the polynomial in u:
\[
q(u) := q(\alpha_1,\cdots,\alpha_{j-1}, \alpha_i + u , \alpha_{j+1}, \cdots, \alpha_n)
\]
Since $$q(0) \neq 0$$, $$q$$ is not the zero polynomial in $$\mathbb{Q}[u]$$. By choosing $$u \neq 0$$ as a rational number to avoid the
finitely many roots of $$q$$, we get $$q(u) \neq 0$$ and $$\hat{\alpha}_j = \alpha_i + u \neq \alpha_i$$.
But then also $$\sigma_i(\alpha) \neq \sigma_j(\alpha)$$ for $$i \neq j$$, since $$\alpha$$ has pairwise distinct coordinates $$\alpha_k \neq \alpha_l$$ to
the given basis $$\sigma_1(\theta),\cdots,\sigma_n(\theta)$$. The rational and separable polynomial
\[
\prod_{i=1}^n (x -\sigma_i(\alpha))
\]
is irreducible in $$\mathbb{Q}[x]$$, since the Galois group operates transitively on the roots.
Let $$a_i := g_i(\sigma_1(\alpha),\cdots,\sigma_n(\alpha))$$ for $$i=1,\cdots,m$$.
Then we have $$a:=(a_1,\cdots,a_m)$$ is an element of $$V_\mathbb{G}$$ and also
\[
p(t,a_1,\cdots,a_m) = \sum_{i=0}^n (-1)^i s_i(a_1,\cdots,a_m) t^{n-i}
\]
\[
= \sum_{i=0}^n (-1)^i s_i(g_1(\sigma_1(\alpha),\cdots,\sigma_n(\alpha)),\cdots,g_m(\sigma_1(\alpha),\cdots,\sigma_n(\alpha))) t^{n-i}
\]
\[
= \sum_{i=0}^n (-1)^i e_i(\sigma_1(\alpha),\cdots,\sigma_n(\alpha)) t^{n-i}
\]
\[
= \prod_{i=1}^n (t -\sigma_i(\alpha))
\]
is an irreducible polynomial in $$\mathbb{Q}[t]$$. Furthermore we have
$$Q(a_1,\cdots,a_m) \neq 0$$, which means that $$Q_j(a_1,\cdots,a_m) \neq 0$$ for all $$j=1,\cdots,r$$, which was to be shown.
This note can be downloaded from here (A note in Galois Theory, Orges Leka) as a pdf file.
Dienstag, 29. November 2016
Tabelle zum Wertverlust pro Jahr bei Gebrauchtwagen
In diesem Post wollen wir den Wertverlust bei Gebrauchtwagen ermitteln.
Als Datensatz zur Beantwortung dieser Frage dient uns folgender Datensatz welcher von Ebay Kleinanzeigen stammt und Informationen zu über 370000 Gebrauchtwagen enthält. Um den durchschnittlichen Preis pro Gebrauchtwagen in Abhängigkeit vom Erstzulassungsjahr, Kilometerstand und Leistung in PS zu ermitteln, benutzen wir folgende mathematische Formel (Lineare Regression, Adjusted R-squared: 0.9047)
\[
\text{ preis } = \exp( a\cdot \text{ jahr } + b\cdot \text{ km } + c \cdot \text{ ps } + d + \epsilon )
\]
wobei die Werte a,b,c,d aus der Regression stammen.
Ein durschnittliches Auto fährt (nach dem Datensatz oben) ca. 12000 km pro Jahr. Der Wertverlust nach einem Jahr lässt sich berechnen als
\[
w = 1- \frac{p'}{p} = 1 - \frac{ \exp(12000\cdot b)}{\exp(a)}
\]
wobei p der aktuelle Preis und p' der Preis in € nach einem Jahr ist.
Setzen wir die Werte für a und b aus der Regression ein, erhalten wir w = 0.119739, d.h. der Werteverlust eines durchschnittlichen Gebrauchtwagens beträgt ca. 12% pro Jahr.
Aus dieser Angabe können wir eine Tabelle erstellen, die uns anzeigt wie sich der Preis eines durchschnittlichen Gebrauchtwagens ungefähr entwickeln wird.
Alle Angaben in der Tabelle sind in € und ohne Gewähr!
| jetzt | nach 1 Jahr | nach 2 Jahren | nach 3 Jahren | nach 4 Jahren | nach 5 Jahren |
|---|---|---|---|---|---|
| 1000 | 880 | 775 | 682 | 600 | 529 |
| 2000 | 1761 | 1550 | 1364 | 1201 | 1057 |
| 3000 | 2641 | 2325 | 2046 | 1801 | 1586 |
| 4000 | 3521 | 3099 | 2728 | 2402 | 2114 |
| 5000 | 4401 | 3874 | 3410 | 3002 | 2643 |
| 6000 | 5282 | 4649 | 4092 | 3602 | 3171 |
| 7000 | 6162 | 5424 | 4775 | 4203 | 3700 |
| 8000 | 7042 | 6199 | 5457 | 4803 | 4228 |
| 9000 | 7922 | 6974 | 6139 | 5404 | 4757 |
| 10000 | 8803 | 7749 | 6821 | 6004 | 5285 |
| 11000 | 9683 | 8523 | 7503 | 6604 | 5814 |
| 12000 | 10563 | 9298 | 8185 | 7205 | 6342 |
| 13000 | 11443 | 10073 | 8867 | 7805 | 6871 |
| 14000 | 12324 | 10848 | 9549 | 8406 | 7399 |
| 15000 | 13204 | 11623 | 10231 | 9006 | 7928 |
Dienstag, 8. November 2016
Mixed Integer Programming to solve a retail category price optimization problem
In this post we are going to implement the procedure given in "A fractional programming approach for retail category price optimization" by S. Subramanian and H. D. Sherali.
We are going to use the SCIP optimization suite with Python bindings.
I have constructed a small example with n = 2 products and m = 3 prices per product.
Here is the python code:
"""
Solves the retail category price optimization in "A fractional programming approach for retail category
price optimization" from S. Subramanian and H. D. Sherali
Copyright (c) by Orges Leka (2016)
"""
from pyscipopt import Model, quicksum
import math
"""
"""
def retail(n,m,P, d, p0, l, u, phi0, phiMax, R0, elast, mu, lmbda, alpha, beta, K, a,b,c,yMin,yMax):
model = Model("retail price")
v, r, g, x, z = {}, {}, {}, {},{}
y = model.addVar(vtype="CONTINUOUS",name="y")
phi = model.addVar(vtype="CONTINUOUS",name="phi")
w = model.addVar(vtype="CONTINUOUS",name="w")
for i in range(1,n+1):
for j in range(1,m+1):
v[i,j] = math.exp(mu[i]+lmbda[i]*P[i,j])
r[i,j] = v[i,j] * P[i,j]
g[i,j] = v[i,j] * (P[i,j] - d[i])
x[i,j] = model.addVar(vtype="CONTINUOUS", name="x(%s,%s)"%(i,j))
z[i,j] = model.addVar(vtype="BINARY",name="z(%s,%s)"%(i,j))
model.addCons(quicksum(v[i,j]*x[i,j] for (i,j) in x) == phi) # 3b
model.addCons( w == math.log(phi0) + elast/(1.0*n) * quicksum( math.log(P[i,j]/p0[i])*z[i,j] for (i,j) in z ) ) # 3d
model.addCons( alpha*phi0 <= phi ) #3e
model.addCons( phi <= phiMax ) # 3e
model.addCons( math.log(alpha*phi0) <= w ) # 3e
model.addCons( w <= math.log(phiMax) ) # 3e
model.addCons( quicksum( r[i,j]*x[i,j] for (i,j) in x ) >= beta * R0 ) #3f
for k in K.keys():
model.addCons( a[k] * quicksum( P[k,l]*z[k,l] for l in range(1,m+1) ) <= b[k] * quicksum( P[k,l] * z[k,l] for l in range(1,m+1) ) + c[k] ) # 3g
for k in K.keys():
model.addCons( a[k] * quicksum( P[k,l]*x[k,l] for l in range(1,m+1) ) <= b[k] * quicksum( P[k,l] * x[k,l] for l in range(1,m+1) ) + c[k]*y ) # 3h
for i in range(1,n+1):
model.addCons( quicksum( z[i,j] for j in range(1,m+1)) == 1) # 3i
for i in range(1,n+1):
model.addCons( quicksum( x[i,j] for j in range(1,m+1)) == y) # 3j
for i in range(1,n+1):
for j in range(1,m+1):
model.addCons( x[i,j] <= yMax * z[i,j] ) # 3k
model.addCons( x[i,j] >= yMin * z[i,j] ) # 3l
model.addCons( yMin <= y ) # 3m
model.addCons( y <= yMax ) # 3m
model.addCons( phi >= alpha*phi0*(1+w-math.log(alpha*phi0)) ) # 4b. T=2
model.addCons( phi >= phiMax*(1+w-math.log(phiMax)) ) # 4b . T = 2
model.addCons( phi <= (phiMax-alpha*phi0)/(math.log(phiMax)-math.log(alpha*phi0))*(w-math.log(alpha*phi0))+alpha*phi0 )# 4a, S= 1
model.setObjective(quicksum(g[i,j]*x[i,j] for (i,j) in x), "maximize") # 3a
print g
return model
def generateExample():
n = 2
m = 3
P = { (1,1):2.49, (1,2):2.59, (1,3) : 2.69,
(2,1):8.99, (2,2):9.09, (2,3) : 9.19 }
d = { 1 : 1.49, 2 : 7.49 }
p0 ={ 1 : 2.50, 2 : 9.05 }
l = { 1 : 2.00, 2 : 8.49 }
u = { 1 : 3.00, 2 : 9.99 }
phi0 = 500
phiMax = 700
R0 = 50
elast = -2.0
mu = { 1 : 0.1, 2: 0.2}
lmbda = { 1: 0.02, 2: 0.01 }
alpha = 0.8
beta = 0.9
K = { 1 : 1}
a = { 1 : 0.5}
b = { 1 : 1.5}
c = { 1 : 0.5}
yMin = 0.0
yMax = 1000.0
return n,m,P, d, p0, l, u, phi0, phiMax, R0, elast, mu, lmbda, alpha, beta, K, a,b,c, yMin, yMax
if __name__ == "__main__":
n,m,P, d, p0, l, u, phi0, phiMax, R0, elast, mu, lmbda, alpha, beta, K, a,b,c,yMin,yMax = generateExample()
model = retail( n,m,P, d, p0, l, u, phi0, phiMax, R0, elast, mu, lmbda, alpha, beta, K, a,b,c,yMin,yMax )
model.hideOutput() # silent mode
model.optimize()
cost = model.getObjVal()
print()
print("Optimized:")
print("Optimal value:", cost)
#model.printAttr("X")
for v in model.getVars():
print(v.name, "=", model.getVal(v))
Please refer to the article for the meaning of the variables.
Freitag, 21. Oktober 2016
Zusammenhang zwischen Rang und Tore im Fussball
Im folgenden Post wollen wir die Daten aus Kaggle analysieren.
In dem Datensatz sind über 25000 Spiele mit 300 Mannschaften vorhanden. Ich habe die Mannschaften absteigend sortiert nach der Gesamtanzahl der Tore, die sie geschossen haben. Diese Sortierung wollen wir Rang nennen. Eine Mannschaft mit vielen Toren steht vor einer anderen Mannschaft mit wenigen Toren, d.h. die erste Mannschaft hat einen niedrigeren Rang als die zweite.
Zwischen dem Rang und der Gesamtanzahl an Toren besteht ein mathematischer Zusammenhang. Dazu wollen wir uns zuerst eine Grafik anschauen.
Wie man sieht werden die Punkte (Rang/Gesamtanzahl an Toren) gut beschrieben durch die grüne Funktion.
Der Zusammenhang ist wie folgt:
\[ T = a_0 + a_1 \cdot \log(R) + a_2 \cdot \log(R)^2 + \epsilon\]
\[ T = 706.037 + 24.20481 \cdot \log(R) - 25.32589 \cdot \log(R)^2 +\epsilon \]
wobei T die Gesamtanzahl der Tore und R der Rang der Mannschaft ist und epsilon eine normalverteilte Zufallsvariable mit Mittelwert 0 und Standardabweichung 21.49643 ist.
Die Berechnungen und die Grafik wurden mit R und MySQL gemacht:
#!/usr/bin/Rscript
source("connectToDB.R")
query <- "select sum(tg) as stg from
(
select home_team_api_id as team_api_id, sum(home_team_goal) tg from game where home_team_api_id is not null and away_team_api_id is not null group by home_team_api_id
union
select away_team_api_id as team_api_id, sum(away_team_goal) tg from game where home_team_api_id is not null and away_team_api_id is not null group by away_team_api_id
) as tmp group by team_api_id order by stg desc;";
x <- dbGetQuery(con, query);
Y <- x$stg
X <- seq(1:length(x$stg))
d <- data.frame(log(X),Y)
names(d) <- c("x","y")
m <- lm(d$y ~ poly(d$x,2,raw=TRUE))
png("rang-tore.png", width = 16, height = 8, units = 'in', res = 600)
plot(d$y,type="p",xlab="Rang der Mannschaft",ylab="Gesamtanzahl an Toren",main="Fussball: Rang und Tore",cex=0.3)
lines(predict(m,d),col="green")
dev.off()
Wir testen, mit dem Kolmogorov-Smirnov-Test in R, ob der Fehler \[\epsilon\] normalverteilt ist:
r <- m$residuals; ks.test(r,"pnorm",mean=mean(r),sd=sd(r))Der Test ergibt:
> ks.test(r,"pnorm",mean=mean(r),sd=sd(r)) One-sample Kolmogorov-Smirnov test data: r D = 0.0721, p-value = 0.08732 alternative hypothesis: two-sidedDa der p-Wert >= 0.05 ist, kann man davon ausgehen, dass epsilon normalverteilt mit Mittelwert 0 = mean(r) und Standardabweichung = sd(r) = 21.49643 ist.
Donnerstag, 20. Oktober 2016
Gebrauchtwagenpreise auf Ebay-Kleinanzeigen
Ich habe mit Scrapy Daten zu Gebrauchtwagenpreisen auf Ebay-Kleinanzeigen gesammelt. Hier ist eine grafische Auswertung nach Erstzulassungsjahr und Preis in Euro:
Die Grafik wurde mit R erzeugt:
#!/usr/bin/Rscript
x <- read.csv("jahr_preise.csv")
ll <- lm(log(x$preis) ~ poly(x$jahr, 93, raw=TRUE))
png("jahr-preis.png", width = 16, height = 8, units = 'in', res = 600)
plot(x$jahr,x$preis,type="p",xlab="Erstzulassungsjahr",ylab="Preis in EURO",main="Gebrauchtwagenpreise auf Ebay-Kleinanzeigen",cex=0.3)
lines(x$jahr, exp(ll$fitted.values))
dev.off()
Um die Kurve in der Grafik darstellen zu können wurde folgende Regression verwendet:
\[ \text{preis} = \exp(\sum_{n=0}^{n=93}{a_n\cdot\text{jahr}^n}) \]
Mittwoch, 13. Juli 2016
Breadth First Search in Python and Java
Breadth-First-Search-Algorithm:
Here is the python code:
You can call it like this:
./bfs.py graph.txt vThe file graph.txt:
v:r r:s,v s:r,w w:t,x,s t:w,x,u x:w,t,u,y u:t,x,y y:x,u
#!/usr/bin/python
import sys
def read_graph(filename):
f = open(filename,'r')
graph = {}
for line in f:
line = line.replace('\n','')
fromVertex, toList = line.split(':')
toList = toList.split(',')
graph[fromVertex] = toList
return graph
def bfs(graph,s):
color = {}
dist = {}
pi = {}
for u in graph.keys():
if u != s:
color[u] = 'white'
dist[u] = None
pi[u] = None
color[s] = 'gray'
dist[s] = 0
pi[s] = None
Q = []
Q.append(s)
while len(Q) > 0:
u = Q.pop(0)
for v in graph[u]:
if color[v] == 'white':
color[v] = 'gray'
dist[v] = dist[u]+1
pi[v] = u
Q.append(v)
color[u] = 'black'
for x in graph.keys():
print x,color[x],dist[x],pi[x]
print "---------------"
return color,dist,pi
def print_path(graph,s,v,pi):
if v == s:
print s
elif pi[v] is None:
print "no path from ", s , " to ", v, " exists"
else:
print_path(graph, s, pi[v], pi)
print v
if __name__ == '__main__':
graph = read_graph(sys.argv[1])
s = sys.argv[2]
color,dist,pi = bfs(graph,s)
Here is the java code:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
public class BFS {
private static HashMap color;
private static HashMap dist;
private static HashMap pi;
public static void bfs(HashMap graph, String s)
{
color = new HashMap();
dist = new HashMap();
pi = new HashMap();
for(String u : graph.keySet())
{
if( !u.equals(s)){
color.put(u, "white");
dist.put(u, null);
pi.put(u, null);
}
}
color.put(s, "gray");
dist.put(s, 0);
pi.put(s, null);
ArrayList Q = new ArrayList();
Q.add(s);
while( Q.size() > 0)
{
String u = Q.get(0);
Q.remove(0);
for(String v : graph.get(u))
{
if( color.get(v).equals("white") )
{
color.put(v, "gray");
dist.put(v, dist.get(u)+1);
pi.put(v, u);
Q.add(v);
}
}
color.put(u,"black");
for( String x : graph.keySet())
{
System.out.println( x + " , " + color.get(x) + " , " + dist.get(x) + " , "+pi.get(x));
}
System.out.println("---------------");
}
}
public static HashMap read_graph(String filename)
{
HashMap graph = new HashMap();
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
String line;
while ((line = br.readLine()) != null) {
String[] splitted1 = line.split(":");
String fromVertex = splitted1[0];
String[] toVertexList = splitted1[1].split(",");
graph.put(fromVertex, toVertexList);
}
} catch (FileNotFoundException e) {
System.out.println("file not found");
e.printStackTrace();
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
return graph;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
HashMap graph = read_graph(args[0]);
bfs(graph,args[1]);
}
}
You can call the java program like this:
java BFS graph.txt vAfter calling the python / java version, you should get something similar to this:
r , gray , 1 , v s , white , null , null t , white , null , null u , white , null , null v , black , 0 , null w , white , null , null x , white , null , null y , white , null , null --------------- r , black , 1 , v s , gray , 2 , r t , white , null , null u , white , null , null v , black , 0 , null w , white , null , null x , white , null , null y , white , null , null --------------- r , black , 1 , v s , black , 2 , r t , white , null , null u , white , null , null v , black , 0 , null w , gray , 3 , s x , white , null , null y , white , null , null --------------- r , black , 1 , v s , black , 2 , r t , gray , 4 , w u , white , null , null v , black , 0 , null w , black , 3 , s x , gray , 4 , w y , white , null , null --------------- r , black , 1 , v s , black , 2 , r t , black , 4 , w u , gray , 5 , t v , black , 0 , null w , black , 3 , s x , gray , 4 , w y , white , null , null --------------- r , black , 1 , v s , black , 2 , r t , black , 4 , w u , gray , 5 , t v , black , 0 , null w , black , 3 , s x , black , 4 , w y , gray , 5 , x --------------- r , black , 1 , v s , black , 2 , r t , black , 4 , w u , black , 5 , t v , black , 0 , null w , black , 3 , s x , black , 4 , w y , gray , 5 , x --------------- r , black , 1 , v s , black , 2 , r t , black , 4 , w u , black , 5 , t v , black , 0 , null w , black , 3 , s x , black , 4 , w y , black , 5 , x ---------------
Mittwoch, 30. September 2015
Computing polynomials with cyclic Galois groups in SAGE
Here is some SAGE code to compute a polynomial with degree \(n\) which has cyclic Galois group.
The computation is done as in the example
https://en.wikipedia.org/wiki/Inverse_Galois_problem#Worked_example:_the_cyclic_group_of_order_three
#!/usr/bin/env spython
import sys
from sage.all import *
from random import sample
from collections import Counter
def t(n,k):
return binomial(n-floor((k+1)/2),floor(k/2))
def alpha(n,k):
return (-1)**(k*(k-1)/2)
def pbin(n):
return sum([alpha(n,k)*t(n,k)*x**(n-k) for k in range(n+1)])
def genCyclicPoly(n):
x = var('x')
k = 0
while True:
p = k*n+1
k += 1
if is_prime(p):
break
y = primitive_root(p)
K = CyclotomicField(p,names='a')
a = K.gen()
o = Mod(y**n,p).multiplicative_order()
s = sum([a**((y**n)**i%p) for i in range(o)])
pol = s.minpoly('x')
return (pol,k-1,p,y)
for n in range(1,40+1):
pol,k,p,y = genCyclicPoly(n)
print n
print pol
print
For example for \(n = \frac{17-1}{2} = 8 \) we get the following polynomial:
\[ x^8 + x^7 - 7x^6 - 6x^5 + 15x^4 + 10x^3 - 10x^2 - 4x + 1 \]
Looking at the coefficients of the polynomial and searching for them in OEIS we find the sequence A065941.
Consider the following polynomial:
\[ p(n,x) = \sum_{k=0}^{n} \binom{n-\left \lfloor \frac{k+1}{2} \right \rfloor}{\left \lfloor \frac{k}{2} \right \rfloor} \cdot (-1)^{\frac{k(k+1)}{2}}\cdot x^{n-k} \]
We conjecture that the following is true (let \(p>2\) be prime):
\[ Gal(p(n,x)) = C_n \Leftrightarrow n = \frac{p-1}{2} \Leftrightarrow p(n,x) \text{ is irreducible }\]
If someone finds a proof or a counterexample to this, please let me know.
An heuristic argument why factoring is difficult
Let \(n=pq\) be the prime decomposition of \(n\) and let \(n=2^e\).
Let us suppose that \(p = q = \sqrt{n}\).
Let \(p_n\) be the probability to have a number \(1 \le x \le n\)
with \(1 < gcd(x,n) < n\) and as such to also have a non-trivial factor of \(n\).
Then we have
\[p_n = 1-\frac{\phi(n)}{n}=1-\prod_{p|n}{(1-\frac{1}{p})} = 1-(1-\frac{1}{p})(1-\frac{1}{q}) \]
\[ = 1-(1-\frac{1}{\sqrt{n}})^2 = 1-(1-\frac{1}{\sqrt{2^e}})^2 \]
Suppose there exists a factoring-algorithm which runs in polynomial time \(f(e)\) and
which draws a number \(x\) at every step and computes \(gcd(x,n)\).
Let \(X\) be the number of numbers \(x\) with \(1 \lt x \lt n\) and \(1 \lt gcd(x,n) \lt n\) which the algorithm
finds after \(f(e)\) steps. Then by definition of the algorithm we must have
\[ 1 = P(X \ge 1) \]
But on the other hand we have
\[ P(X\ge 1) = 1 - P(X=0) = 1 - (1-p_n)^{f(e)} \]
\[= 1-(1-\frac{1}{\sqrt{2^e}})^{2 \cdot f(e)} \]
The last equality is by definition of the algorithm valid for every \(e\).
But for \(e \rightarrow \infty\) we have
\[1 = P(X \ge 1) = 1-(1-\frac{1}{\sqrt{2^e}})^{2 \cdot f(e)} \rightarrow_{e \rightarrow \infty} 0\]
hence for \(e \rightarrow \infty\) we have the contradiction \(1 = 0\).
Candidate One Way Function
The construction of the function goes like this:
The main idea is the construction of a "random" permutation on words of fixed size
and then applying this permutation to the given word.
Let \[w = a_0 \cdot a_1 \cdots a_{n-1} \] be a word from \( \{0,1\}^n \), \(|w| = n\)
Let \[m = \sum_{i=0}^{n-1}{ a_i \cdot 2 ^ {n-1-i} } \] be the corresponding binary number constructed
from the word.
Let \(k= \left \lfloor \frac{n!}{2^n} \right \rfloor \cdot (m+1)\) , then \( 1 \le k \le n! \).
Compute the Lehmer-Permutation \(\pi_k\) from \(k\) on \(n\) numbers.
(
https://en.wikipedia.org/wiki/Factorial_number_system,
https://en.wikipedia.org/wiki/Lehmer_code
)
Set \[ x := \pi_k \cdot w = a_{\pi_k(0)} \cdot a_{\pi_k(1)} \cdots a_{\pi_k(n-1)} \]
Then \[f(w) := x\].
So the function permutes the digits in the word \(w\) and the permutation is determined by \(w\).
One might first ask, why the construction with \(k\) is needed, and why one
might not just compute the Lehmer-Permutation of \(m\) instead.
This is done so that the permutation is better distributed among the numbers \(1 ,\ldots, n!\).
Otherwise since \(2^n << n!\) the permutation \(\pi_m\) will have to many fixed points \(\pi_m(i) = i\)
for \(1 \le i \le L\) for some \(L\) .
One possible attack would be given a word \(x = f(w)\) with \(l\) zeros and \(n-l\) ones, to
consider all words \(y\) with \(l\) zeros and \(n-l\) ones and then compute \(f(y)\) of such words. There are exactly \(\binom{n}{l}\) such words.
This attack would function if \(l\) is either too small or too large.
Since as is known the \(\binom{n}{l}\) takes the maximum value at the central binomial coefficient
(the middle term), we might conjecture, that words with \(l=\frac{n}{2}\) zeros and \(n-l=\frac{n}{2}\) ones are hard
to attack.
But for some random word \(w\), the expeted number of zeros and ones is equal to \(l = n-l = \frac{n}{2}\).
Hence since the central binomial coefficient fullfills the inequality:
\[\binom{n}{n/2} \ge \frac{2^n }{ \sqrt{2 \cdot n} } \]
we might conjecture, that the work to be done to invert such words is exponential in \(n\).
Here are some small examples, all words of length \(n = 4\):
m=0, n=4, k=1 Lehmer-Code = (Factorial-Digits of m) = [0, 0, 0, 0] pi_k = [0, 1, 2, 3] w= [0, 0, 0, 0] pi_k*w= [0, 0, 0, 0] m=1, n=4, k=2 Lehmer-Code = (Factorial-Digits of m) = [0, 0, 1, 0] pi_k = [0, 1, 3, 2] w= [0, 0, 0, 1] pi_k*w= [0, 0, 1, 0] m=2, n=4, k=3 Lehmer-Code = (Factorial-Digits of m) = [0, 1, 0, 0] pi_k = [0, 2, 1, 3] w= [0, 0, 1, 0] pi_k*w= [0, 1, 0, 0] m=3, n=4, k=4 Lehmer-Code = (Factorial-Digits of m) = [0, 1, 1, 0] pi_k = [0, 2, 3, 1] w= [0, 0, 1, 1] pi_k*w= [0, 1, 1, 0] m=4, n=4, k=5 Lehmer-Code = (Factorial-Digits of m) = [0, 2, 0, 0] pi_k = [0, 3, 1, 2] w= [0, 1, 0, 0] pi_k*w= [0, 0, 1, 0] m=5, n=4, k=6 Lehmer-Code = (Factorial-Digits of m) = [0, 2, 1, 0] pi_k = [0, 3, 2, 1] w= [0, 1, 0, 1] pi_k*w= [0, 1, 0, 1] m=6, n=4, k=7 Lehmer-Code = (Factorial-Digits of m) = [1, 0, 0, 0] pi_k = [1, 0, 2, 3] w= [0, 1, 1, 0] pi_k*w= [1, 0, 1, 0] m=7, n=4, k=8 Lehmer-Code = (Factorial-Digits of m) = [1, 0, 1, 0] pi_k = [1, 0, 3, 2] w= [0, 1, 1, 1] pi_k*w= [1, 0, 1, 1] m=8, n=4, k=9 Lehmer-Code = (Factorial-Digits of m) = [1, 1, 0, 0] pi_k = [1, 2, 0, 3] w= [1, 0, 0, 0] pi_k*w= [0, 0, 1, 0] m=9, n=4, k=10 Lehmer-Code = (Factorial-Digits of m) = [1, 1, 1, 0] pi_k = [1, 2, 3, 0] w= [1, 0, 0, 1] pi_k*w= [0, 0, 1, 1] m=10, n=4, k=11 Lehmer-Code = (Factorial-Digits of m) = [1, 2, 0, 0] pi_k = [1, 3, 0, 2] w= [1, 0, 1, 0] pi_k*w= [0, 0, 1, 1] m=11, n=4, k=12 Lehmer-Code = (Factorial-Digits of m) = [1, 2, 1, 0] pi_k = [1, 3, 2, 0] w= [1, 0, 1, 1] pi_k*w= [0, 1, 1, 1] m=12, n=4, k=13 Lehmer-Code = (Factorial-Digits of m) = [2, 0, 0, 0] pi_k = [2, 0, 1, 3] w= [1, 1, 0, 0] pi_k*w= [0, 1, 1, 0] m=13, n=4, k=14 Lehmer-Code = (Factorial-Digits of m) = [2, 0, 1, 0] pi_k = [2, 0, 3, 1] w= [1, 1, 0, 1] pi_k*w= [0, 1, 1, 1] m=14, n=4, k=15 Lehmer-Code = (Factorial-Digits of m) = [2, 1, 0, 0] pi_k = [2, 1, 0, 3] w= [1, 1, 1, 0] pi_k*w= [1, 1, 1, 0] m=15, n=4, k=16 Lehmer-Code = (Factorial-Digits of m) = [2, 1, 1, 0] pi_k = [2, 1, 3, 0] w= [1, 1, 1, 1] pi_k*w= [1, 1, 1, 1]As one can see for \(m=9\) and \(m=10\) (we have in both cases \(\pi_k \cdot w = 0011\)), the function is in general neither surjective nor injective. I have implemented this idea in python, and here is a nontrivial example on \(150\) bits which runs in under one second even though implemented in python:
w = [1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0] m=1279607855208070195064338423740863454312235238, n=150, k=51223701589084024400750942404902242134696092112154131410359938801887859702545711950279545972412289530642923770897655341449893740303460239109720926509319367414721427119543767321207725214681463099908033034573794457858117619817707577286035424763678710865742056652800 pi_k = [134, 72, 4, 119, 108, 25, 91, 73, 112, 107, 32, 29, 54, 58, 80, 8, 94, 123, 38, 36, 69, 135, 127, 51, 141, 20, 124, 106, 83, 97, 82, 44, 55, 27, 3, 138, 52, 113, 118, 43, 147, 59, 34, 132, 45, 26, 121, 24, 18, 2, 11, 6, 126, 130, 81, 12, 48, 139, 1, 142, 46, 47, 120, 71, 88, 140, 104, 100, 23, 40, 143, 63, 9, 122, 136, 5, 67, 105, 33, 57, 84, 15, 49, 76, 98, 102, 111, 70, 41, 60, 86, 16, 13, 89, 22, 77, 17, 61, 129, 75, 21, 131, 62, 19, 95, 117, 78, 101, 109, 56, 90, 68, 7, 137, 53, 110, 146, 30, 125, 14, 96, 28, 50, 31, 114, 37, 148, 93, 144, 145, 133, 115, 92, 149, 87, 64, 42, 65, 79, 66, 39, 85, 74, 35, 128, 116, 103, 99, 10, 0] pi_k * w = [1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1]Here is the python code, to compute the function:
#!/usr/bin/python
import math
from itertools import permutations
import random
def getPermFromLehmer(fnr,n):
# gives the permutation from lehmer-code:
# for example 4041000 -> (4,0,6,2,1,3,5)
l = range(n)
perm = []
for d in fnr:
perm.append(l.pop(d))
return perm
def getPermutations(n):
perms = permutations(range(0,n))
return list(perms)
def getFactoradicDigits(num,d):
digits = []
i = 1
while num > 0:
rem = num % i
num = num / i
i += 1
digits.append(rem)
digits.reverse()
diff = d - len(digits)
newDigits = diff * [0]
newDigits.extend(digits)
return newDigits
def getLehmerCode(p):
if len(set(p)) != len(p):
return "is not a permutation"
else:
l = []
for i in range(len(p)):
pi = p[i]
di = len([1 for pj in p[(i+1):] if pj < pi ])
l.append(di)
return l
def getFactoradicNumber(perm):
lehmerCode = getLehmerCode(perm)
n = len(perm)
return sum([lehmerCode[i]*math.factorial(n-1-i) for i in range(n)])+1
def getPermFromNr(n,d):
return getPermFromLehmer(getFactoradicDigits(n-1,d),d)
def getRandomBits(n):
return [random.randint(0,1) for i in range(n)]
def computeNFromBits(r):
l = len(r)
return sum([2**(l-1-i)*r[i] for i in range(l)])
def applyPerm(perm,l):
if not len(perm)==len(l):
return None
else:
return [l[perm[i]] for i in range(len(perm))]
def f(bits):
m = computeNFromBits(bits)
if m == 0:
m = 1
n = len(bits)
k = int(math.floor(math.factorial(n)/(2**n*1.0)))*(m+1)
print "m=%s, n=%s, k=%s" % (m,n, k)
perm = getPermFromNr(k,len(bits))
print "pi_k = %s" % perm
bitsPerm = applyPerm(perm,bits)
return bitsPerm
def digits(n,d):
k = n
dig = []
while k> 0:
dig.append(k%d)
k = k/d
dig.reverse()
return dig
def computeAll(m):
p = getPermutations(m)
for i in range(0,2**m):
r = digits(i,2)
if len(r) < m:
diff = (m-len(r))*[0]
r.reverse()
r.extend(diff)
r.reverse()
rPerm = f(r)
print "w= %s" % r
print "pi_k*w= %s" % rPerm
for x in p:
print x, getLehmerCode(x), getFactoradicNumber(x), getPermFromNr(getFactoradicNumber(x),m)
if __name__=='__main__':
computeAll(3)
r = getRandomBits(150)
rPerm = f(r)
print "w= %s" % r
print "pi_k*w= %s" % rPerm
If someone has an idea on how to invert the function, please let me know.
Directed Graphs in PostgreSQL
In this post we want to make use of CTE in PostgreSQL to compute paths in directed graphs.
We consider only the edges of the graphs, this means, that if some graph has a vertex without any
edge in or out of this vertex, it is not shown here.
Given the edges of some graph, we want to construct the startpoints and endpoints only of paths, which are not contained in other paths.
First we want to construct some different graphs and we want also to note the desired output of the query when applied to the specific graph,
to clarify what our solution should do.
Lets start with a graph wich consinsts of three components:
drop table if exists p; create table p( startPoint integer, endPoint integer); -- example 1: delete from p; insert into p(startPoint, endPoint) values (4,3),(2,5),(5,20),(1,10),(10,15),(15,16),(16,18); -- desired output of example 1: -- startpoint | endpoint | distance | path --------------+----------+----------+--------------- -- 1 | 18 | 4 | 1,10,15,16,18 -- 2 | 20 | 2 | 2,5,20 -- 4 | 3 | 1 | 4,3In the above example, we do not want to see for example startpoint=10, endpoint=16, distance=2 and path=10,15,16 because this path is already contained in the first path of the above table, which starts at 1 and ends at 18. Now we want to take a look at a more complex example. In the following graph, we have two components and also paths of interest which are of length two, namely 1,4.
-- example 2: delete from p; insert into p(startPoint,endPoint) values (3,9),(9,2),(9,10),(10,7),(3,17),(1,4),(6,5),(5,9); -- desired output of example 2: -- startpoint | endpoint | distance | path --------------+----------+----------+------------ -- 1 | 4 | 1 | 1,4 -- 3 | 2 | 2 | 3,9,2 -- 3 | 7 | 3 | 3,9,10,7 -- 3 | 17 | 1 | 3,17 -- 6 | 2 | 3 | 6,5,9,2 -- 6 | 7 | 4 | 6,5,9,10,7In this example we have several starting points occuring more than once, namely 3 and 6 which is ok, since they correspond to different paths. What about cycles in a graph? Should the query go in an infinte loop? Should it terminate, and if it terminates, what should the output be? Here is the most simple cyclic graph with more than one vertex: It makes sense, that the query terminates, and if some component of the graph contains a loop, than this component should not be shown. In the above graph, the result would be an empty table:
-- example 3: (graph contains cycles) delete from p; insert into p(startPoint, endPoint) values (1,2),(2,1); -- desired output of example 3: -- startpoint | endpoint | distance | path --------------+----------+----------+------ -- notice that in this example the desired output is an empty table, since it makes no sense to define the starting and the end poin of a cycle;What happens if a graph contains multiple routes from the same starting and endpoints? Here a small graph : In this case all paths should be shown. (One might consider an alternative solution for example, to take only the shortest or the longest path.):
-- example 4: (graph contains multiple routes) delete from p; insert into p(startPoint, endPoint) values (1,2),(2,3),(1,3); -- desired output of example 3: -- startpoint | endpoint | distance | path --------------+----------+----------+------- -- 1 | 3 | 1 | 1,3 -- 1 | 3 | 2 | 1,2,3In the last example, we want to consider a graph which has more than one component one of which contains a cycle and the other not: Here we want to show only the paths of the component which has no cycle:
-- example 5: (graph contains two components, one of which contains a cycle, the other not) delete from p; insert into p(startPoint, endPoint) values (1,2),(2,1),(3,4),(4,5); -- notice that in this example, it makes sense to ignore the component of the graph which contains a cycle and to just show the paths of the other components which do not have a cycle -- desired output of example 4: -- startpoint | endpoint | distance | path --------------+----------+----------+------- -- 3 | 5 | 2 | 3,4,5All this can be done with CTE in PostgreSQL, which at this time is not available in MySQL. The basic idea to recursively define a table is the same as the definition of a recursive function. In the recursive function you need some starting value. This starting value is implemented through a "starting table", or "starting query". This query is then "UNION [ALL]" to the recursive part. One solution is:
with recursive t(intermediatePoint,startPoint,endPoint,distance,path) as (
select
( select greatest(max(startPoint),max(endPoint)) from p)+1 as intermediatePoint,
startPoint, endPoint, 1 as distance, cast(startPoint as text) || ',' || cast(endPoint as text) from p
union all
select t2.startPoint as intermediatePoint, t1.startPoint, t2.endPoint,1+t2.distance, cast(t1.startPoint as text) || ',' || t2.path from p t1, t t2
where t1.endPoint = t2.startPoint
and 1+t2.distance <= (select count(*) from p)
) select startpoint, endpoint,distance,path from t
where
startPoint not in (select intermediatePoint from t)
and endPoint not in (select intermediatePoint from t)
order by startpoint, endpoint;
To keep track if some path is contained in some other path, we keep track of intermediate points, when joining together two paths. In this way we can later recognize if
some edge is an intermediate point or not. If the starting or ending points have been considered to be intermediate points, than the corresponding entry is not shown, because this means,
that this path is contained in some other path.
Since paths of length two (edges) do not have intermediate points, but we have to assign them also a value, because of "UNION [ALL]", on idea would be to assign them the value NULL.
Unfortunotely this did not work. I guess this is becaus in the definiton of the recursive table t(intermediatPoint,startPoint,endPoint,distance,path) we have nothing said about the data-types of the columns involved, for example of the column intermediatePoint. So I guess, to determine the data-type of this column, the data-type of the corresponding column before the "UNION-ALL" is taken, but this guess might be wrong. So in order to have some value of which is distinct from all edges, I decided to take the maximum over all edges and add one to it.
To avoid the query to go into an infinte loop when it tries to join paths of a cycle, we make use of the following observation:
The start and endpoints with corresponding paths which are of interest to us can have at most a length which is equal to the number of edges in the graph.
This would correspond to, a graph of consecutive integers where there is an edge from every integer n to n+1 for example 1,2,3,..,100,101.
Samstag, 25. April 2015
SQL-Query to compute start- and endpoints of consecutive integers in a given list of distinct integers
In this post we want to compute the starting and ending points of consecutive integers in a given list of distinct integers.
Consider the following table:
1,2,3,4;
6 ;
16,17,18,19;
21;
26, 27, 28, 29
We want to compute the starting and the end points of those sequences, which are:
1,4
6,6
16,19
21,21
26,29
We will do this, by first computing the starting points, then the end points and then do a join on them:
A sequence of distinct integers are consecutive if and only if
( maximal number in sequence - minimal number in sequence + 1 ) = ( number of integers in sequence)
For example consider the consecutive sequence:
5,6,7,8
We have:
8 - 5 + 1 = 4
On the other hand consider the following sequence which is not consecutive:
1,2,3,10
We have:
10-1+1 = 10 != 4
Here is the solution found at Joe Celko adopted to the above table with minor modification:
Consider the following table:
drop table if exists p; create table p ( proj_start integer primary key); insert into p values (1),(2),(3),(4),(6),(16),(17),(18),(19),(21),(26),(27),(28),(29);In this table we have the following sequences of consecutive integers:
1,2,3,4;
6 ;
16,17,18,19;
21;
26, 27, 28, 29
We want to compute the starting and the end points of those sequences, which are:
1,4
6,6
16,19
21,21
26,29
We will do this, by first computing the starting points, then the end points and then do a join on them:
select
startPoints.proj_start start, min(endPoints.proj_start) end
from
(
select min(proj_start) proj_start from p
union
select p2.proj_start from p p1, p p2 where p1.proj_start < p2.proj_start group by p2.proj_start having p2.proj_start > max(p1.proj_start)+1
) as startPoints, # compute the starting points of the sequences
(
select p1.proj_start from p p1, p p2 where p1.proj_start < p2.proj_start group by p1.proj_start having min(p2.proj_start)>p1.proj_start+1
union # we have to take the last point because it is not in the above query:
select max(proj_start) as proj_start from p
) as endPoints # compute the end points of the sequences
where startPoints.proj_start <= endPoints.proj_start group by startPoints.proj_start
;
There are also other solutions to this problem (See for example Joe Celko's , SQL For Smarties, Advanced SQL Programming, Fourth Edition, Chapter 32.3, page 600). One solution makes use of the following observation for sequences of consecutive integers:A sequence of distinct integers are consecutive if and only if
( maximal number in sequence - minimal number in sequence + 1 ) = ( number of integers in sequence)
For example consider the consecutive sequence:
5,6,7,8
We have:
8 - 5 + 1 = 4
On the other hand consider the following sequence which is not consecutive:
1,2,3,10
We have:
10-1+1 = 10 != 4
Here is the solution found at Joe Celko adopted to the above table with minor modification:
select min(proj_start) start, item end from
(
select p1.proj_start, max(p2.proj_start) item from p as p1
inner join p as p2
on p1.proj_start <= p2.proj_start and
(p2.proj_start - p1.proj_start +1)
= (select count(*) from p as p3 where p3.proj_start between p1.proj_start and p2.proj_start)
group by p1.proj_start
) x group by item;
Abonnieren
Posts (Atom)








