Sunday, July 5, 2015

Implications

This blog is a continuation of the FCA blog. I actually mused over this in Summer 2004, but wanted to recap for myself and share some source code.

The article I read back then was Endliche Hüllensysteme und ihre Implikationenbasen (Finite hull systems and their implications). I summarize this article here, since I didn't find an english version online.

In short, a context is constructed, where rows are subsets of attributes ''A'', i.e. elements of the power set, and columns are implications between subsets and the incidence is given by respects ( ), H = {2A, 2A × 2A, ⊢} . This context is simplified, by applying the Armstrong rules, to form a non-redundant, complete, reduced context, named B . Then an algorithm is presented, which takes the intents of some context and recursively constructs the respected implications using B and afterwards uses the 3rd Armstrong rule to find an easy set of implications, i.e. not necessarily minimal, but easier than the Duquenne-Guiges-Basis.

Definitions

  • U → V : an implication is a pair (U, V) , U ⊆ M and V ⊆ M U is premiss and V conclusion.
  • WU → V : A set W respects (U, V) , if UWorV ⊆ W . One also says: (U, V) holds for W .
  • If V ⊆ U the implication is called trivial.

An intelligent system repeatedly gets sets of elements (attributes) as input (objects) and associates these elements. Implications are the result of many such sets.

  • A concept lattice C respects (U, V) , iff U’ ⊆ V .
  • (U, V) holds in C , iff V ⊆ U’’

Implications can be composed to give new implications. The minimal set of implications that produce all other implications is called an implication basis.

A minimal implication basis is given by the Duquenne-Guiges-Basis (stem basis), which consists of all pseudo-contents:

Let X ↦ X’’ be a closure operation, then P is pseudo-closed if

  • P  ≠  P’’
  • Q ⊂ P  ⇒  Q’’ ⊆ P

There cannot be a implication basis with less implications, than the Duquenne-Guiges-Basis, but one can choose implications that are easier (with low |U||V| , U → V with V ≠ ∅ and UV = ∅ ).

Construction of H

H = {2A, 2A × 2A, ⊢} is a context and the according concepts C(H) = {(O, A)} are subsets (= objects of H ) that respect a set of implications (= attributes H ).

The basic implications ( ⇒  ) respected by this context C ( ) are given by the Armstrong Axioms:

 ⇒ {U → U}  (A1) {U → V}  ⇒ {UW → U}  (A2) {U → V, VW → Z}  ⇒ {UW → Z}  (A3)

Some derived ones are ( ≡  is  ⇒  in both directions):

{U → V}  ≡ {U → UV}  (A4) {U → V, U → W}  ≡ {U → VW}  (A5) {U → V}  ≡ {W → V|U ⊆ W}  (A6) {U → V, UVW → Z}  ≡ {U → V, UW → Z}  (A7)

Note

Notation: UV means UV and Ui means U∪{i}

H can be constructed inductively. The sequence of the attributes is of no importance when constructing the power set.

Note

In [1] {⋆} named the new attribute in the step n and {⋆⋆} in the step n + 1 . Here I name them i and j and becomes a wild card meaning whatever element in a previous step.

In the following i means a new attribute. Because of A4:{X → Y}  ≡ {X → XY} only implications with sets U ⊆ V are included, therefore Ui → V is not there.

  • Ho = 1 , because ∅⊢∅ → ∅ .
  • Lo = 0 , because ∅⊬∅ → {i} .
Hn + 1 =  ⊢  U → V U → Vi Ui → Vi X Hn Ln 1 Xi Hn Hn Hn
  • (2, ⋆) implications hold with Xi = X∪{i} , because X respects U → V at location (1, 1) .
  • The L in (1, 2) is discussed below
  • The 1 in (1, 3) is because UiX makes the implication hold.

Ln + 1 is part of Hn + 2 , which adds another element j .

Ln + 1 =  ⊢  U → Vy U → Vij Ui → Vij X Ln Ln 1 Xi Ln Ln Ln
  • The columns of Ln + 1 are those of Hn + 1 augmented by j at the conlusion side.
  • The rows are the same as in Hn + 1 .
  • As i , so is j not in X and we can distribute L to all but (1, 3) , where UiX makes it hold.

Construction of B

Because of A5 ({U → V, U → W}  ≡ {U → VW} ) we can reduce H to implications of the shape U → U∪{i} , abbreviated U → i (thus Ui → j means U∪{i} → U∪{i, j} .

In the following names the extra element on the right of a previous recursion step, whichever that was.

B is in analogy to H horizontally subdivided by three event:

  • no new element i , ie some other of a previous step is on the right.
  • with i on right side
  • with i on both sides: the extra element on the right is any of a previous step.
B1 =  0 1       A1 =  0 1 0 0
Bn + 1 =  ⊢  U → ⋆  U → i Ui → ⋆ X Bn An 1 Xi Bn 1 Bn
  • (1, 3) : UiX , so it holds.
  • (2, 2) : XiU → i . If UX , so is UiXi , ie it holds; same for  ⊆  .
  • (1, 1) ⇒ (2, 1), (2, 3) : XU → ⋆ ≡ XiU → ⋆ ≡ XiUi → ⋆
  • (1, 2) : see below

An + 1 is part of Bn + 2 , which adds another element j on the right side. The new element of step n (i ) can be on the left side or not, hence the horizontal partitioning.

An + 1 =  ⊢  U → j Ui → j X An 1 Xi An An

The implications (columns) in B are reduced. The rows are reduced apart from the last line, which is always full.

Application to Find Implications for a Context

H , L , B , A ( = X ) are used to find the implication basis and the intents.

We recursively construct the composed context KX defined by X(K(g)) , g is object of K .

Every attribute of K(g) = g gets a position. This position says whether the attribute is there or not there - column after the if in the following formulas. So every g is coded by a binary number. This is λ:2M↦{0, 1}n in [1].

The first two lines for (g[n])Hn show the according implication coding. This is κ:(UV)↦{0, 1, 2}n with 2 = i ∈ U , 1 = i ∈ V and UV = ∅ in [1]. So every binary attribute coding becomes a ternary implication coding.

For n = 1

(g[1])H1 =  1, 0, 1 1, 1, 1    (g[1])L1 =  0, 0, 1  if g1 = 0 0, 0, 0  if g1 = 1

For n > 1

(g[n])Hn =  0   1   2 U → V U → Vi Ui → Vi (g[n − 1])Hn − 1  (g[n − 1])Ln − 1  13n − 1  if gn = 0 (g[n − 1])Hn − 1  (g[n − 1])Hn − 1  (g[n − 1])Hn − 1  if gn = 1
(g[n])Ln =  (g[n − 1])Ln − 1  (g[n − 1])Ln − 1  13n − 1  if gn = 0 (g[n − 1])Ln − 1  (g[n − 1])Ln − 1  (g[n − 1])Ln − 1  if gn = 1

The recursive construct with coding 1 = x ∈ V < 2 = x ∈ U shows that the column position, interpreted as ternary number, codes the implication. If the incidence at the column position is 1, then g respects this implication: {g’}Hn is indicator function for the respected implications.

The coding will also place a larger V before a smaller one when going from right to left. This way one can filter out implications with already encountered same left side.

The UV will be closed. If there is no implication for a left side, this is a closed intent, too.

Note

Python Implementation

Python's arbitrary precission integers is used for coding. An attribute's position is the bit position of the integer. Every object is thus an integer. A context is a list of integers.

In here higher bits are more left; in the [1] they are more right; the horizontal order is inverted.

def UV_H(Hg,gw):
    """
    Return implications UV respecting g.
    gw = g width
    Hg = H(g), g is the binary coding of the attribute set
    UV = all non-trivial (!V⊂U) implications U->V with UuV closed; in ternary coding (1=V,2=U)
    K = all closed sets
    """
    lefts = set()
    K = set()
    UV = set()
    p = Hwidth(gw)
    pp = 2**p
    while p:
        pp = pp>>1
        p = p-1
        if Hg&pp:
            y = istr(p,3,gw)
            yy = y.replace('1','0')
            is02 = y.find('1') == -1 #y∈{0,2}^n
            if is02:
                K.add(y)
            elif yy not in lefts:
                lefts.add(yy)
                UV.add(y)
    return (UV,K)

Now we do the analogue procedure with the B context. In B the implications are of the shape U → U∪{x} , so we need to specify U and the one binary position of x. This implication coding can be derived from the column position recursively (see below).

For n = 1 :

(g[1])B1 =  0 1    (g[1])A1 =  0 1  if g1 = 0 0 0  if g1 = 1

For n > 1 :

(g[n])Bn =  U → ⋆  U → i Ui → ⋆ (g[n − 1])Bn − 1  (g[n − 1])An − 1  1(n − 1)2n − 2  if gn = 0 (g[n − 1])Bn − 1  12n − 1  (g[n − 1])Bn − 1  if gn = 1
(g[n])An =  U → j Ui → j (g[n − 1])An − 1  12n − 1  if gn = 0 (g[n − 1])An − 1  (g[n − 1])An − 1  if gn = 1

The following Python returns the implication coding for a column t .

Awidth = lambda n: 2**n
Bwidth = lambda n:n*2**(n-1)
def A012(t,i):
    if i<0:
        return ""
    nA = Awidth(i)
    if t < nA:
        return "0"+A012(t,i-1)
    else:
        return "2"+A012(t-nA,i-1)
def B012(t,i):
    """
    Constructs ternary implication coding (0=not there, 2=U, 1=V)
    t is B column position
    i = |M|-1 to 0
    """
    if not i:
        return "1"
    nA = Awidth(i)
    nB = Bwidth(i)
    nBB = nB + nA
    if t < nB:
        return "0"+B012(t,i-1)
    elif t < nBB:
        return "1"+A012(t-nB,i-1)
    else:
        return "2"+B012(t-nBB,i-1)

The positions of the 1's in the B row for a given g yield the implications. Here the python source code:

def UV_B(Bg,gw):
    """
    returns the implications UV based on B
    Bg = B(g), g∈2^M
    gw = |M|, M is the set of all attributes
    """
    UV = []
    p = Bwidth(gw)
    pp = 2**p
    while p:
        pp = pp>>1
        p = p-1
        if Bg&pp:
            uv = B012(p,gw-1)
            UV.append(uv)
    return UV

To get the implications that hold in a context K , i.e. for intent 1 and intent 2 and ..., we &-combine (multiply) the B rows for intent 1 and intent 2 and ...

Note

See pyfca for the full and possibly updated source code.

Constructing a Basis

The implications that result via B can be pruned by

  • first finding the minimal antichain
  • then applying the 3rd Armstrong

The minimal Antichain

The 1-position (j) in the ternary coding is called significant component. Lj are all implications with the same significant component.

The implications U → j constructed in this way via KB are ordered lexicographically based on 0 ≤ 1 ≤ 2 .

They are also ordered with the product order, which is a partial order, and it depicts the containment hierarchy of the U side. We want to find the smallest U of every chain in Lj . This minLj is an antichain and so is L = ∪minLj .

The UV_B above changed to return this minimal antichain:

def v_Us_B(Bg,gw):
    """
    returns the implications {v:Us} based on B
    v is the significant component
    Bg = B(g), g∈2^M
    gw = |M|, M is the set of all attributes
    """
    v_Us = defaultdict(list)
    p = Bwidth(gw)
    pp = 2**p
    while p:
        pp = pp>>1
        p = p-1
        if Bg&pp:
            uv = B012(p,gw-1)
            #lets find minima regarding product order
            #{v:[Umin1,Umin2,...]}
            v = uv.find('1')#v=significant
            u = uv[:v]+'0'+uv[v+1:]
            u = int(u.replace('2','1'),2)
            Umin_s = self[gw-v-1]#bit position from right
            it = [i for i,U in enumerate(Umin_s) if U&u==u]
            for i in reversed(it):
                del Umin_s[i]
            else:
                Umin_s.append(u)
    return v_Us

The Basis

In the construction of the minimal antichain the 2nd Armstrong rule has been used, but there is still redundancy due to the 3rd Armstrong rule {U → V, VW → Z}  ⇒ {UW → Z} .

A component-wise operation is created to represent the 3rd Armstrong rule for the 0,1,2-coding

  • UVW ⇒ UW : 0○0 = 0 and 2○0 = 0○2 = 2○2 = 2 This is a binary or operation.
  • VVW ⇒ UW , no V in UW : 1○2 = 2○1 = 0 .
  • Z ⇒ Z , VZ = ∅ : 1○0 = 0○1 = 1
  • LiLj = {xy|x ∈ Li, y ∈ Lj, i ≠ j}

Note that it is required that, with X → x and Y → y , x ∈ Y xor y ∈ X to make this the 3rd Armstrong rule.

This is implemented in python as

#u1,u2 code the attribute sets via the bits of an integer
#v1,v2 are bit indices
#u1->v1, vv1 = 2**v1
#u2->v2, vv2 = 2**v2
if vv2&u1 and not vv1&u2:
    return (v1,[(u1|u2)&~vv2])
elif vv1&u2 and not vv2&u1:
    return (v2,[(u1|u2)&~vv1])

The properties of are:

  • xy = yx
  • x ≠ xy ≠ y
  • If x ≤ ny , then xy ≤ ny ,  ≤ n is the product order
  • If xy ∈ Li , then x ∈ Li or y ∈ Li (note: Li not minLi )
  • If there exits xy = z ∈ L , then there exist ,  ∈ L with  = z

The objective is to find Y ⊆ L , of which the repeated application of produces L : Y = L .

Y is defined as

  • Y2 = YY
  • Yn + 1 = Yn∪{z ∈ L|z = xy, x ∈ Yn, y ∈ YYn} This means that of Yn○(YnY) only elements in L are added at each step. But the algorithm below can cope with Yn getting bigger than L.
  • Y = ∪n ≥ 2Yn
  • Y = Y∪○Y

One starts with Y0 = L (LL) , i.e. all those elements of L that are not results of an application of the 3rd Armstrong rule. As long as Yn ≠ L , we add z ∈ L Yn to Yn . Yn∪{z} cannot generate elements of Y0 , but it can generate elements of Zn = Yn Y0 . Therefore we do Yn + 1 = Y0∪(Zn (○(Ynz)))∪z , i.e. we also remove elements, but only those that can be generated together with z , hence Yn ⊂ Yn + 1 .

Note

The formula Yn + 1 = Y0∪(Zn (○(Ynz)))∪{z} in [1] lets you think, that only the current z can generate itself. But actually other z ∈ Zn could generate themselves. Zn (○(Ynz)) could remove elements other than z that are needed for the generation of elements in Yn , thus making Yn¬ ⊂ Yn + 1 . Still the latter is postulated in [1]. There is a comment, though, that states, one should use disjunct union. This is interpreted as: don't remove elements of Zn , where the current z is not involved in the generation.

Here ist the python code for that:

def basis_minomega(self):
    L = self
    Y = L - (L*L)
    while True:
        Ybar = Y + ~Y
        take = L - Ybar
        if not len(take):
            return Y
        else:
            z = next(take.flatten())
            Yzgen = Y**z #generate with z involved
            Y = (Y - Yzgen) + z

Note

This algorithm can generate a basis that is smaller regarding ω(UV) = |U||V| , but not necessarily in count compared to the Duquenne-Guiges-Basis.

[1](1, 2, 3, 4, 5, 6) Endliche Hüllensysteme und ihre Implikationenbasen by Roman König.

Sunday, June 28, 2015

Formal Concept Analysis

My Motivation

A had my first contact with Formal Concept Analysis (FCA) in Summer 2004. At the time I did some experiments in python, which I want to share here. Later on I became too busy again with work and other projects. Writing about it is also a refresher to myself.

My first motivation that made me google and find FCA was DB related.

As an example let's take (Givenname,Familyname). You can do either (G,iG)1-n(iG,F) and you will have many family names F occurring more than once (n>1 times) or you can do (G,iF)m-1(iF,F) and you will have many given names G occurring more than once (m>1 times).

To avoid this you would do

(G,iG)m-n(iF,F)  ⇒  (G,iG)1-m(iG,iF)n-1(iF,F)

This way a given name and a family name would be there once and you would reference each of them.

One can repeat the process, if there are more columns. This is called DB normalization.

  • Basically whenever a combination of values turns up more then once one would have to make an extra table. This extreme normally is not done.
  • Actually the foreign key is still repeated instead. Something like run-length encoding would mean referencing tables instead of rows in tables. It is possible but not relational database like.
  • Normally you end up having a lot of repeats in a table. This flattening of data and thereby ignoring the context is the reason for probability.

My previous blog was What is Information. There I identify the omnipresent variable, understood as a set to exclusively choose from, as a fundamental building block of information processing.

In FCA the basic variable is binary: distinguishable elements of a set, called attributes, are either there or not there together, and such a subset of the set of attributes is an object.

The next step of an information processing system, in order to reduce the memory usage, is to find, which of the attributes are exclusive in a context, and thus form a new variable.

A DBs is designed by a human. The analysis leading to tables/variables is done in our mind. How is the algorithm we perform in our mind? How could this 'intelligence be done artificially'? It seemed quite basic to information processing. People quite dynamically create variables, relate them, and categorize them based on certain properties or usages of relevance to the task at hand.

For me two questions are important.

  • How does our mind come up with variables and how do we organize them?
  • What is the most (memory) efficient way to do it?

Years before I had come across an article and subsequently the Web site of Gerard Wolff, which considers compression the basis of computing.

During university time I also had some contact with artificial neural network. It has some commonalities with FCA, like Hebb rule, which associates stimuli and thus forms concepts in a parallel fashion.

Definitions

Basic starting point is the context, but not the diffuse context of everyday language, but mathematically well confined.

K = (O, A, I)
  • K is called context.
  • O is a set of objects.
  • A is a set of attributes.
  • I ⊂ O × A is the incidence.

2 = {1, 2} and 2A denotes the power set. For subsets Os ⊂ O (Os ∈ 2O ) and As ⊂ A (As ∈ 2A ) one defines these mappings:

  • from a subset of O (Os ) to a subset of A (As ):
2O → 2A OKs = Os’ = {a ∈ A|∀o ∈ Os(o, a) ∈ I}
  • and vice versa
2A → 2O AKs = As’ = {o ∈ O|∀a ∈ As(o, a) ∈ I}

K is represented as a table where rows are objects and columns are attributes.

Note that K(o) = oK = o’ : = {o}K maps O → 2A and that AKs ≠ K(As) = {K(a)|a ∈ As} .

The context is called clarified, if there are no duplicate rows or columns: K(o) = o and K(a) = a are injective.

K(K(o)) = o’’ and K(K(a)) = a’’ are closure operation.

C = {c|c = (Os’’, Os’) = (As’, As’’), Os ∈ 2O, As ∈ 2A} = {O, A} is a concept lattice. Every concept node in the lattice consists of a set of objects and a set of attributes. Nodes further up have more objects and nodes further down have more attributes. If the sets of objects (attributes) of the one above is a superset (subset) of the objects (attributes) of the one below, then these nodes are linked; they are comparable and form a chain. For neighboring linked nodes, the one above is called successor, the one below predecessor. Two links meet when moving downward and they join upward.

meet = infimum = :

Cs  = {∩Os’’, ∪Os’}

join = supremum = :

Cs  = {∪Os’’, ∩Os’}

The s subscript is iterated over after the mapping has been done.

The is a logical or (union) of the extents. The is a logical and (intersection) of the intents.

The partial ordering is by convention based on the extent (objects) and not the intent (attributes) of concepts. One can, though, regard the attributes as objects and the objects as attributes: The two concept lattices are called dual to each other.

Attributes or objects that don't produce new nodes in the lattice, but are only an addition to already existing nodes, can be removed. The intent of such objects (extent of such attributes) are equal to the intersection of other intents (extents). Removing them will produce a reduced context.

Two concepts that can be compared (a < b ), will meet in a and join in b . If not comparable they will join or meet somewhere else, say c . c is comparable to a and b . Possibly they will join at the top or meet at the bottom.

Discussion

Here some thoughts of interest to me, skimming the surface, asking for further explorations.

The open sets in a topology

  • The empty set and X itself are open.
  • Any union of open sets is open.
  • The intersection of any finite number of open sets is open.

can be compared to concepts. The set X can be identified as attributes.

The concept lattice is the result of many (open set) inputs.

A chain can be seen as an extensive quantity, whose elementary constituents are a selection of attributes. In a one-dimensional crossing of a chain the attributes can be ordered by the time they meet the chain. 'How far down' from a starting point would be a metric for these attributes.

If going down the chain we have a regular pattern of meeting 2 new attributes, then we deal with a 2-dimensional space. The shortest distance determines, which attributes belong to which dimension. This thread leads to geometry.

Elementary attributes are the intents of the nodes just below top. It is waisted resources linking them to top. Instead in a lattice they can be identified by their links downward, by their topology.

Due to the topology induced ordering it is possible to address the attributes via counting, i.e. via combinations of concepts. That is the start of analytical descriptions and of languages.

In the context every attribute was linked to every object with a switch: there xor not there (bit). N attributes that are exclusive can consume less than N bits memory by using combinations: logN bits. Concepts ai are (locally) exclusive if they meet with a concept b in the pattern aib = ci . So the ai form a variable and the ci are a function of a1 , i.e. they can be constructed instead of stored.

A variable is a meta-concept. A variable doesn't need to be linked to every individual value (=concept), if a linear ordering is available to allow intervals. When each of a set of attributes (concepts) meets with each of another set, a 2-dimensional space is spanned (cartesion product). Here analytic descriptions of shapes allow to reduce memory usage.

These analytical elements are also concepts, concepts with parameters: they are called functions in programming. When these functions with formal parameters meet actual parameters, they generate concepts. To address space-time tradeoff the generated concepts must stay around for some time.

The actual parameters must fit to the formal parameters in the requirements imposed by the functions. These requirements are another important kind of concepts: types.

The links in a concept lattice don't have any order. When mapped to a linear memory space a linear order is automatically overlaid, though. If a linear order is inherent to concepts due to their topology, then it's natural to keep this order in memory. Else mechanisms must be installed for the linking that don't use the linear order of the memory space.

If (almost) all combination of concepts are there a natural representation in linear binary memory is by mapping the concepts to bits. Every concept is then an arbitrary precission integer

If the purpose of the combinations is to address exclusive concepts a register machine's addressing capabilities are best put to work.

Actual links, adjustable, like via synapses in the brain, are more kindred to concept lattices.

Register machines with more or less hardware implemented functions (instruction set), can be regarded as an extraction of the analytical features of our brain, first evolved via biological evolution, then via the science culture. Many algorithms developed address special application and are surely very efficient there.

I regard FCA as a connection to the starting points of this development and therefore to consider in a venture to artificially reproduce analytic capabilities of our brain.

Experiments in Python

Since my first contact with FCA new algorithms have been devised to efficiently make a concept lattice, i.e. construct all concepts. In-Close, In-Close2, CbO, FCbO seem to be among the currently fastest ones. (from Comparing Perfomance of Algorithms for Generating Concept Lattices (Kurznetsov)).

My experiments were with older algorithms: NextConcept, Neighbors and AddIntent.

While writing this blog, I've decided to make a github repository pyfca to collect some algorithms in python.

So far it includes a python implementation of the AddIntent algorithm from AddIntent: A New Incremental Algorithm for Constructing Concept Lattices and a lattice drawing algorithm I had taken from Galicia. So it can be used to create a concept lattice (fca_lattice) and to draw it (lattice_diagram) either using tkinter() or svg().inkscape().

My intention is to add more algorithms in times of leisure. A collaborative effort could be more comprehensive. Therefore: Contributions are very welcome.

Sunday, March 15, 2015

What is Information?

What is Information?

What is Information?

This is a very fundamental question that promises insight to all our intellectual activities and beyond.

The word information is ubiquitous and of course we know what it means. We would describe it as: something that reduces our uncertainty. Are we happy with suchlike descriptions? They use words, which again need clarification, which again can be decomposed into smaller parts. As long as you still can abstract away, you are not done.

Note

First you abstract until you can't abstract no more.
Then you synthesize.

Still, we need to start with the natural usage of the word. We talk about information in newspapers, in books, in sentences, in words.

What is involved?

  • a sender: a person, an animal, our environment,...

  • a message: written or spoken text, signs, ...

  • a receiver: again a person, a computer, a radio, ...

    This is communication. Is Communication = Information? No, it's communication of information.

We need to decompose more: A person has a brain with a map of our world, with concepts. A message consists of words of a natural language, but it can also consist of signs, Chinese pictographic characters, hieroglyphs, bits or bytes....

These and other things we can think of, are all quite different. Still they must have something in common.

They are a multitude
A multitude of concepts in the brain
A multitude of brain cells, of synapses
A multitude of phonemes
A multitude of photoreceptors in the eye
A multitude of colors
A multitude of voltages in the radio receiver
A multitude of frequencies in the radio signal
A multitude of words or letters or signs in a message

A person as a sender consists of many parts, these parts all communicate as well.

What is the smallest part of a communication processes?

Selection from a multitude

Note

First a multitude, then the selection. That's evolution. Evolution is how all dynamic systems work.

  • This is how biological evolution works. Selection by environment.
  • Economy: supply/demand = creation of multitude; publicity, offers, comparison = selection
  • The brain: ideas = creating multitude = creativity; selection via comparison with sensory input and experience
  • Sciences: papers = multitude; research, studying = selection
  • Memetics: ideas communicated to others
  • Culture in societies
  • ...

We have abstracted everything away and remain with a multitude. In mathematics the foundation is set theory. The set is what we so far called multitude.

Note

Where are we now? We have a

  • set of elements
  • a way to choose or select

One instance of choosing means to choose exactly one element. By selecting one element we de-select the others. The elements are exclusive.

Regarding choosing or selecting in relation to the set theory one might want to check out the axiom of choice.

With this exclusiveness added the best words I came up with are variable and value.

Note

set --> variable element --> value

Value and variable turn up everywhere: in programming, in physics, in statistics,..., because they are the building blocks of everything: They are information.

Note

building block for information = variable = set of exclusive values

Value and variable are quite ubiquitous and thus appropriate for something as fundamental as information.

Let's get quantitative: What is the smallest amount, we can choose from? The answer: 2. The important aspect quantitatively is only the size of the variable, also called cardinality. For a variable V I shall denote the size with |V|. It makes sense to use the smallest variable, the bit (B of size |B| = 2), as unit of measurement for information. Values of bigger variables can be mapped to combinations of bits, which are elements of the Cartesian product. n bits can create |Bn| = 2n combinations.

Note

The information of V is how many bits do we need to select a value of V.

Because 2log2|V| = |V| we get

IV = log2|V|

Note

Information as a measure is a property of a variable, not of its values.

The occurrences of values of a variable need to be distinguished from the variable itself. They make another variable. When the focus is on the occurrences, one can use the word variate. Let's denote this variable with V. To select an occurrence of any value of V we need log|V| bits.

The frequency of occurrence is yet another variable. Here we look at pi = |Vi| ⁄ |V|. ipi = 1. Something like this is called a probability. The exclusiveness is essential to it. It is a measure.

Note

Add probability for or , but only for exclusive values of the same variable, else in general p(ab) = p(a) + p(b) − p(a b) holds. Note that p(ab) = p(a b).

Multiply probability for and, but only for values belonging to independent variables else p(a b) = p(a)p(b|a) holds. See below.

One can select values of V, i.e. Vi, by first selecting an occurrence of any value (log|V|) and then subtract the excess selection done (log|Vi|): log|V| − log|Vi| =  − logpi. Via this selection path one can do with less bits to reference the total amount of occurrences:  − i|Vi|logpi ≤ |V|log|V|. Dividing both sides by |V| we get the average bits needed to select a value of V. It is called entropy (S).

SV =  − ipilogpi SV ≤ IV

IV is the upper limit of SV. IV can also be expressed with the SV formula by using a uniform pi = 1 ⁄ |V|.

IV is the upper limit of SV. Considering that a variable is always embedded in a context of other variables, this limit case vaguely can be interpreted as loss of structure.

Note

The entropy is the average number of bits needed to select a value of the variable.

The occurrences of values of a variable are due to the variable's environment (= context), i.e. its relation to other variables. This context is often unknown or too complex (= too much information) to describe. It might also be known and used to derive the frequency of occurrences of values (a priori probability).

Physical systems can be regarded as a huge set of variables.

There is even a deeper relation between between energy and information. Check out these links: - Physics of information - Statistical physics - Statistical thermodynamics


So far information was regarded as inherent to a variable (= a piori).

I continue with the perspective of a learning system, like humans and other animals or learning machines (computers).

A learning system needs to provide as much memory as there is in the observed system to fix one state.

But often the learning system is confronted with a system too complex (= too much information) to create a complete map of it. It doesn't see all the variables. Most of them stay hidden (latent variables). In this situation including the frequency of occurrences of values, i.e. the probability, is often the best thing one can do. The probability distribution is a result of hidden dependencies from hidden variables.

Or it is due to the limited information content of nature itself, i.e. due to quantum mechanics. With probability distributions quantum mechanics can continue to use the well known continuum mathematics (real numbers,...), although the major statement of quantum mechanics is, that there is no continuum.

In such a complex system it normally is not possible to select a single value of a variable. Then one resorts to a partial selection via a probability distribution for the variable. This method includes also the case of selecting one value via a dirac distribution, the entropy of which is 0. A larger entropy expresses an more imprecise selection or, when talking about predictions, more uncertainty about what to expect.

For an exactly fixated value of one variable we often can predict the value of another variable via a functional dependency.

Note

Functions are important, because there is no information needed to fix the value of the dependant variable.

With an imprecise selection and an imprecise relation, analytical expressions for dependencies are often not feasible. Then one resorts to conditinal probability: p(a|b) (probability of a given b), a ∈ A and b ∈ B.

It is

p(ab) = p(a)p(b|a) = p(b)p(a|b)

Note

p(a)p(a|b) does not make sense.

This is Bayes Theorem. It allows to derive p(b|a) from p(a|b), i.e. the inverse dependency (corresponding to inverse function in exact mathematics). The starting variable's distribution is the prior and the dependent variable's distribution is the posterior.

There is a probability distribution for B for every value of A (p(b|a) ∈ p(B|a)): bp(b|a) = 1. But for p(b|a) as a function of a (likelihood funcion) there is no such normalization. In general p(B|ai) and p(B|aj) can actually be completely unrelated.

Based on theoretical reasoning and assumptions, i.e by creating a model (= finding variables and their dependency), one normally ends up using a predefined distribution, like the normal distribution. The parameters of such a distribution often need to be estimated based on measurements. There are two related methods to do this:

  • There is the fundamental principle of maximum entropy (ME). By maximizing the entropy one does not assume more or make a more precise selection than what is actually known.

    Via a Bayesian inference one gets p(a|{bi}) = p(a)(p({bi}|a))/(p({bi})) (p({bi}|a) = ip(bi|a)) for the (parameter) variable A and then one can maximize the entropy of this distribution and take the a ∈ A with maximum p(a|{bi}). For a uniform p(a) this yields the same result as ...

  • Maximum likelihood (ML). It selects a ∈ A such that ip(bi|a) becomes a maximum.

The product () is an assumption that the observed bi values belong to independent and identical distributions (i.i.d).

Here some links regarding ML and ME: 1, 2, 3.


For more on information and probability I recommend these great books:


Whether values are exclusive in the first place, i.e. are variables, depends on the context, i.e. on the values of other variables. An intelligent system can find out the exclusiveness by observation. Only then it can observe the frequency of values with respect to other values of the same variable.

Monday, February 23, 2015

Lenovo E145 with Archlinux

Lenovo E145 with Archlinux

Lenovo E145 with Archlinux

Because of the purportedly long battery live I recently purchased the Lenove E145 notebook as an occasional travel companion. I replaced the 500Gb HDD with a Crucial M550 SSD.

Archlinux Installation

Download archlinux iso.

Copy it to a USB stick

sudo dd bs=4M if=/media/sw/linux/archlinux-2015.02.01-dual.iso of=/dev/sdc && sync

Boot with the USB stick.

Then create the partitions:

gdisk /dev/sda
  • 34-2047 bios boot (ef02)
  • +4G linux swap (8200)
  • rest linux filesystem (8300)

Make file system.

mkswap /dev/sda2
swapon /dev/sda2
mkfs.ext4 /dev/sda3

Note

Check for TRIM capability.

hdparm -I /dev/sda | grep TRIM

Positive. One should later on regularly do

fstrim /

The archlinux base system

mount /dev/sda3 /mnt
pacstrap /mnt base base-devel
genfstab -p /mnt >> /mnt/etc/fstab
arch-chroot /mnt

with basic Configure

echo E145 > /etc/hostname
hwclock --systohc --utc
ln -sf /usr/share/zoneinfo/Europe/Vienna /etc/localtime
#Uncomment the needed locales in /etc/locale.gen
locale-gen
echo LANG=en_US.UTF8 > /etc/locale.conf
#
#this has escape where capslock was
#/usr/share/kbd/keymaps/i386/qwerty/myus.map.gz
cat >> /etc/vconsole.conf << "EOF
KEYMAP=myus
FONT=lat2-14
EOF

Replacing keyboard with sd-vconsole in the HOOKS list produced strange glyphs in XTerm. I had to revert it later.

mkinitcpio -p linux #ignore the warnings
passwd

Install grub and reboot

pacman -S grub
#in /etc/default/grub: GRUB_CMDLINE_LINUX_DEFAULT="quiet resume=swap_partition"
grub-install --target=i386-pc --recheck /dev/sda
grub-mkconfig -o /boot/grub/grub.cfg
exit
umount -R /mnt
reboot

Add user

useradd -m -g users -G audio,lp,optical,storage,video,wheel,games,power,scanner -s /bin/bash <user>
passwd <user>

Check hardware and kernel modules:

lspci
lspci -k
lsmod

E145 lspci:

00:00.0 Host bridge: Advanced Micro Devices, Inc. [AMD] Family 16h Processor Root Complex
00:01.0 VGA compatible controller: Advanced Micro Devices, Inc. [AMD/ATI] Kabini [Radeon HD 8240 / R3 Series]
00:01.1 Audio device: Advanced Micro Devices, Inc. [AMD/ATI] Kabini HDMI/DP Audio
00:02.0 Host bridge: Advanced Micro Devices, Inc. [AMD] Family 16h Processor Function 0
00:02.2 PCI bridge: Advanced Micro Devices, Inc. [AMD] Family 16h Processor Functions 5:1
00:02.3 PCI bridge: Advanced Micro Devices, Inc. [AMD] Family 16h Processor Functions 5:1
00:02.5 PCI bridge: Advanced Micro Devices, Inc. [AMD] Family 16h Processor Functions 5:1
00:10.0 USB controller: Advanced Micro Devices, Inc. [AMD] FCH USB XHCI Controller (rev 01)
00:11.0 SATA controller: Advanced Micro Devices, Inc. [AMD] FCH SATA Controller [AHCI mode]
00:12.0 USB controller: Advanced Micro Devices, Inc. [AMD] FCH USB OHCI Controller (rev 39)
00:12.2 USB controller: Advanced Micro Devices, Inc. [AMD] FCH USB EHCI Controller (rev 39)
00:13.0 USB controller: Advanced Micro Devices, Inc. [AMD] FCH USB OHCI Controller (rev 39)
00:13.2 USB controller: Advanced Micro Devices, Inc. [AMD] FCH USB EHCI Controller (rev 39)
00:14.0 SMBus: Advanced Micro Devices, Inc. [AMD] FCH SMBus Controller (rev 3a)
00:14.2 Audio device: Advanced Micro Devices, Inc. [AMD] FCH Azalia Controller (rev 02)
00:14.3 ISA bridge: Advanced Micro Devices, Inc. [AMD] FCH LPC Bridge (rev 11)
00:18.0 Host bridge: Advanced Micro Devices, Inc. [AMD] Family 16h Processor Function 0
00:18.1 Host bridge: Advanced Micro Devices, Inc. [AMD] Family 16h Processor Function 1
00:18.2 Host bridge: Advanced Micro Devices, Inc. [AMD] Family 16h Processor Function 2
00:18.3 Host bridge: Advanced Micro Devices, Inc. [AMD] Family 16h Processor Function 3
00:18.4 Host bridge: Advanced Micro Devices, Inc. [AMD] Family 16h Processor Function 4
00:18.5 Host bridge: Advanced Micro Devices, Inc. [AMD] Family 16h Processor Function 5
01:00.0 Network controller: Broadcom Corporation BCM43142 802.11b/g/n (rev 01)
03:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller (rev 07)
04:00.0 Unassigned class [ff00]: Realtek Semiconductor Co., Ltd. RTS5229 PCI Express Card Reader (rev 01)

Install yaourt from AUR using the Archlinux Build System (ABS):

pacman -S abs
#download yaourt 1.5 from AUR
cd ~/abs/yaourt
makepkg -s
pacman -U yaourt-1.5-1-any.pkg.tar.xz

Other utilities:

pacman -S gvim, sudo, git

Network

Ethernet works straight away.

Wireless

I had read that there are problems with broadcom-wl-dkms, but so far it worked for me:

yaourt -S broadcom-wl-dkms
depmod -a
modprobe wl

/etc/modprobe.d/broadcom-wl-dkms.conf:

blacklist b43
blacklist b43legacy
blacklist ssb
blacklist bcm43xx
blacklist brcm80211
blacklist brcmfmac
blacklist brcmsmac
blacklist bcma

/etc/systemd/system/network.service:

[Unit]
Description=Network Connectivity
Wants=network.target
Before=network.target
BindTo=sys-subsystem-net-devices-<nic>.device
After=sys-subsystem-net-devices-<nic>.device

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=ip link set dev <nic> up
ExecStart=ip addr add <ip address>/24 dev <nic> #CIDR notation
ExecStart=ip route add default via 192.168.1.1
ExecStop=ip addr flush dev <nic>
ExecStop=ip link set dev <nic> down

[Install]
WantedBy=multi-user.target

I use netctl and made a static setup for ethernet and a dynamic for wireless.

/etc/netctl/sen:

Description='static ethernet connection'
Interface=enp3s0
Connection=ethernet
IP=static
Address=('192.168.1.107/24')
Gateway='192.168.1.1'
DNS=('192.168.1.1')
ExcludeAuto=no

/etc/netctl/dwl:

Description='dhcp wireless home'
Interface=wlp1s0
Connection=wireless
Security=wpa
IP=dhcp
ESSID='whateveryouressid'
Key='whateveryourpassphrase'

wifi-menu -o can be used to scan for wifi and to generate a profile.

Audio

pacman -S alsa-utils
pacman -S mplayer
pacman -S pavucontrol

Alsa configuration files:  ⁄ usr ⁄ share ⁄ alsa ⁄ alsa.conf includes  ⁄ etc ⁄ asound.conf and  ⁄ .asoundrc .

Commands for testing

#check loaded kernel modules
lsmod | grep snd
#check indices
cat /proc/asound/modules
#cards, devices, ...
cat /proc/asound/cards
aplay -l
aplay -L
arecord -l
arecord -L

#testing
arecord -r 48000 test.wav
aplay test.wav

and the alsa configuration file:

/etc/asound.conf:

pcm.dmixed {
    ipc_key 1025
    type dmix
    slave.pcm "hw:1,0"
}

#one called "dsnooped" for capturing
pcm.dsnooped {
    ipc_key 1027
    type dsnoop
    slave.pcm "hw:1,0"
}

#and this is the real magic
pcm.asymed {
    type asym
    playback.pcm "dmixed"
    capture.pcm "dsnooped"
}

#a quick plug plugin for above device to do the converting magic
pcm.pasymed {
    type plug
    slave.pcm "asymed"
}

pcm.!default {
    type plug
    slave.pcm "asymed"
}

defaults.ctl.!card 1;

#a ctl device to keep xmms happy
ctl.pasymed {
    type hw
    card 1
    device 0
}

#for aoss:
pcm.dsp0 {
    type plug
    slave.pcm "asymed"
}

ctl.mixer0 {
    type hw
    card 1
    device 0
}

pcm.jackplug {
    type plug
    slave { pcm "jack" }
}

pcm.jack {
    type jack
    playback_ports {
        0 alsa_pcm:playback_1
        1 alsa_pcm:playback_2
    }
    capture_ports {
        0 alsa_pcm:capture_1
        1 alsa_pcm:capture_2
    }
}

Somewhere I had found that position_fix would help for the crackling microphone.

/etc/modprobe.d/audio_powersave.conf:

options snd_hda_intel model=thinkpad position_fix=3 power_save=1

It maybe helps a little bit, but the actual way to tackle this is via alsamixer, F4, capture to maximum and the other two bars down to zero.

Video

pacman -S xorg-server
pacman -S xorg-init
pacman -S xorg-utils
pacman -S xorg-xmodmap #because I have .Xmodmap file

#video
pacman -S xf86-video-ati

Mouse

#mouse pad
pacman -S xf86-input-synaptics

Window Manager

I use xmonad, but the choices are many ...

pacman -S xmonad
pacman -S xmonad-contrib

Special Keys

The special keys of the E145 are turned on by default. So you have to press Fn to get to the Fx keys. Enter BIOS at boot and set them to legacy to have F1 through F12 directly.

The special keys are then available via Fn+Fx. They don't work out of the box, but are mapped to X events already. These X events can be mapped to commands via xbindkeys.

pacman -S xbindkeys

~/.xbindkeysrc:

"amixer -D pulse sset Master 5%+"
    XF86AudioRaiseVolume

"amixer -D pulse sset Master 5%-"
    XF86AudioLowerVolume

"amixer -D pulse set Master toggle"
    XF86AudioMute

"amixer -D pulse set Capture toggle"
    XF86AudioMicMute

"echo `cat /sys/class/backlight/radeon_bl0/brightness` -10 | bc | sudo tee /sys/class/backlight/radeon_bl0/brightness > /dev/null"
    XF86MonBrightnessDown

"echo `cat /sys/class/backlight/radeon_bl0/brightness` +10 | bc | sudo tee /sys/class/backlight/radeon_bl0/brightness > /dev/null"
    XF86MonBrightnessUp

#not mapped
#XF86Display , XF86AudioNext , XF86AudioPlay , XF86AudioPrev , XF86WebCam , XF86WLAN

Use xbindkeys -v for testing. xbindkeys is started via ~/.xinitrc:

if [ -d /etc/X11/xinit/xinitrc.d ]; then
  for f in /etc/X11/xinit/xinitrc.d/*; do
    [ -x "$f" ] && . "$f"
  done
  unset f
fi
setxkbmap -option terminate:ctrl_alt_bksp
xsetroot -cursor_name left_ptr
xmodmap ~/.Xmodmap
xbindkeys
exec xmonad

Note

Xbacklight didn't work and trying all the other tools would have meant learning about all of them and investigating problems for all of them, so in the above .xbindkeysrc I went for directly writing to /sys/.../brightness. To overcome the permission denied I did

visudo
#add line: <myuser> ALL=NOPASSWD:/usr/bin/tee,/sys/class/backlight/radeon_bl0/brightness

Fan

When I had turned on the E145 for the first time, I was disappointed about the fan noise. The fan started very frequently. Luckily this can be solved using the fancontrol service.

pacman -S lm_sensors
sensors
cat /sys/class/hwmon/hwmon0/device/temp1_input

/etc/modprobe.d/fancontrol.conf:

options thinkpad_acpi fan_control=1

The fancontrol configuration file can be generated by pwmconfig. I edited it afterwards to these values:

/etc/fancontrol:

INTERVAL=10
DEVPATH=hwmon0=devices/platform/thinkpad_hwmon
DEVNAME=hwmon0=thinkpad
FCTEMPS=hwmon0/device/pwm1=hwmon0/device/temp1_input
FCFANS= hwmon0/device/pwm1=hwmon0/device/fan1_input
MINTEMP=hwmon0/device/pwm1=70
MAXTEMP=hwmon0/device/pwm1=100
MINPWM=hwmon0/device/pwm1=30
MAXPWM=hwmon0/device/pwm1=255
MINSTART=hwmon0/device/pwm1=32
MINSTOP=hwmon0/device/pwm1=30
systemctl enable fancontrol
systemctl start fancontrol

Fancontrol stops after returning from sleep, i.e. after having had the lid closed. The following helps

/etc/systemd/system/sleep.target.wants/onsleep.service:

[Unit]
Description=sleep hook
Before=sleep.target
StopWhenUnneeded=yes

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStop=-/usr/bin/systemctl restart fancontrol

[Install]
WantedBy=sleep.target

Battery on command line.

pacman -S acpi
acpi

I use Oh-my-zsh and there I tweaked the kiwi theme.

~/.oh-my-zsh/themes/my.zsh-theme:

PROMPT='%{$fg_bold[green]%}┌[%{$fg_bold[cyan]%}%D %T%{$fg_bold[green]%}]-(%{$fg_bold[white]%}%2~%{$fg_bold[green]%})-$(git_prompt_info)$(svn_prompt_info)$(battery_pct_prompt)
└> % %{$reset_color%}'

ZSH_THEME_GIT_PROMPT_PREFIX="[%{$reset_color%}%{$fg[white]%}git:%{$fg_bold[white]%}"
ZSH_THEME_GIT_PROMPT_SUFFIX="%{$fg_bold[green]%}]-"

ZSH_THEME_SVN_PROMPT_PREFIX="[%{$reset_color%}%{$fg[white]%}svn:%{$fg_bold[white]%}/"
ZSH_THEME_SVN_PROMPT_SUFFIX="%{$fg_bold[green]%}]-"

~/.zshrc:

export ZSH=$HOME/.oh-my-zsh
export EDITOR=vim
test -r ~/.profile && source ~/.profile
bindkey -v

#my = kiwish changed to %D %T
export ZSH_THEME="my"
eval `dircolors ~/.dircolors`
plugins=(battery git mercurial vi-mode)
source $ZSH/oh-my-zsh.sh

Note

The battery installed is not supported by this system and will not charge. Please replace the battery with the correct lenovo battery for this system. Press the ESC key to continue.

On my model this message appeared on startup after a few boots. First I thought it was a wrong warning, but it turned out, the battery was completely discharged: the notebook went black. I removed and reattached the battery and plugged in the notebook and luckily the message didn't appear any more.

Suspend

Suspend to mem works (mem > /sys/power/state). When closing the lid this state is automatically entered.

Hibernate did not work for me.

The resume kernel option

GRUB_CMDLINE_LINUX_DEFAULT="quiet resume=70d8aac3-344d-434d-b607-e48447692734"

did not help here. The GUID is my swap partition.

I stopped investigating regarding this, because the default sleep is just fine for me.