# convert map and possibly given neuron activation frequencies
# into the transition properties of a binary automaton
#
# ARGV[1] : *tree.dat file
# ARGV[2] : map file
#

BEGIN {
  FS = "/"
  if(thresh <= 0) thresh = .33
}

/^[^#]/ {

  if(ARGIND == 2) {

    vn = $2 + 0

    split($3,arr," ")

    vc = arr[4] + 0

    if(vn < 1 - thresh && vn > thresh)
      vn = vc = 2
    else {
      vn = int(vn + thresh)
      ++frq[vn]               # count state vn neurons
    }

    if(vn == 2 || (vc < 1 - thresh && vc > thresh))
      vc = vn = 2
    else
      vc = int(vc + thresh)

    if(DEB) print vn, $2, "  ", vc, arr[4]

    if(vn != 2) {
      ++cfrq[vc]
      ++nfrq[vn]
      icfrq[vc] += ifrq[$1]
      infrq[vn] += ifrq[$1]
    }

    ++cnt[vn" "vc]

    icnt[vn" "vc] += ifrq[$1]

    ++nr
  }
  else {               # use *.tree.dat to extract act. frqs.

    split($0,arr, " ")

    ifrq[arr[1]] = arr[3]
  }
}

END {

  print "#filename(s)"
  print ARGV[1], ARGV[2]
  print ""

  sum = frq[0] + frq[1]
  isum = infrq[0] + infrq[1]

  print "#neurons / neurons active according to threshold " thresh
  print nr, sum
  print ""

  print "#state / rel. neuron count / [ activation frequency]"
  for(e in frq)
    print e, frq[e] / sum, infrq[e] / isum

  print ""

  isum = 0.

  print "#x <- y -- transition / rel. occurrance in map / probability"

  for(e in cnt) {
    print e, cnt[e] / nr, icnt[e]
    if(index(e,2) <= 0) isum += icnt[e]
  }


  ####### normalizations according to valid neuron activations ########

  for(e in cnt) icnt[e] /= isum


  sum = nfrq[0] + nfrq[1]        # number of valid transitions
  nfrq[0] /= sum
  nfrq[1] /= sum

  for(e in cnt) cnt[e] /= sum


  sum = cfrq[0] + cfrq[1]
  cfrq[0] /= sum
  cfrq[1] /= sum

  sum = icfrq[0] + icfrq[1]
  icfrq[0] /= sum
  icfrq[1] /= sum

  print ""
  print "# valid neuron state frq. / valid context state frq. "
  print 0, nfrq[0], cfrq[0]
  print 1, nfrq[1], cfrq[1]

  print ""

  print "#x <- y -- transition / cond. map transition frq. / [ cond. act. based frq.]"
  for(e in cnt)
    if((c = substr(e,3,1)) < 1.5)
      print e, cnt[e] / cfrq[c], icnt[e] / icfrq[c]

  print ""
  print ""
  print ""
}

