Exemplo n.º 1
0
def hook4(lattice):
    global offset
    lattice.logger.info("Hook4: SVG (polyhedral expressions).")
    graph = nx.Graph(lattice.spacegraph)  #undirected
    cellmat = lattice.repcell.mat
    projected = np.dot(cellmat, proj)
    queue = []
    for ring in cr.CountRings(graph).rings_iter(8):
        deltas = np.zeros((len(ring), 3))
        d2 = np.zeros(3)
        for k, i in enumerate(ring):
            d = lattice.reppositions[i] - lattice.reppositions[ring[0]]
            d -= np.floor(d + 0.5)
            deltas[k] = d
            dd = lattice.reppositions[ring[k]] - lattice.reppositions[ring[k -
                                                                           1]]
            dd -= np.floor(dd + 0.5)
            d2 += dd
        # d2 must be zeros
        if np.all(np.absolute(d2) < 1e-5):
            comofs = np.sum(deltas, axis=0) / len(ring)
            deltas -= comofs
            com = lattice.reppositions[ring[0]] + comofs + offset
            com -= np.floor(com)
            # rel to abs
            com = np.dot(com, projected)
            deltas = np.dot(deltas, projected)
            queue.append((com, deltas))
    # translate = -(cellmat[0,:]+cellmat[1,:]+cellmat[2,:])/2
    svg = sw.Drawing()
    for com, deltas in sorted(queue, key=lambda x: x[0][2]):  #key is z of com
        svg.add(face(com, deltas, svg))
    print(svg.tostring())
    lattice.logger.info("Hook4: end.")
Exemplo n.º 2
0
def hook2(lattice):
    logger = getLogger()
    logger.info("Hook2: Show rings in Yaplot format.")
    # copied from svg_poly
    graph = nx.Graph(lattice.graph)  #undirected
    cellmat = lattice.repcell.mat
    s = ""
    s += yp.Layer(2)
    s += yp.Color(0)
    for i, j in graph.edges():
        pi, pj = lattice.reppositions[i], lattice.reppositions[j]
        d = pj - pi
        d -= np.floor(d + 0.5)
        s += yp.Line(pi @ cellmat, (pi + d) @ cellmat)
    for ring in cr.CountRings(graph, pos=lattice.reppositions).rings_iter(
            lattice.largestring):
        deltas = np.zeros((len(ring), 3))
        d2 = np.zeros(3)
        for k, i in enumerate(ring):
            d = lattice.reppositions[i] - lattice.reppositions[ring[0]]
            d -= np.floor(d + 0.5)
            deltas[k] = d
        comofs = np.sum(deltas, axis=0) / len(ring)
        deltas -= comofs
        com = lattice.reppositions[ring[0]] + comofs
        com -= np.floor(com)
        # rel to abs
        com = np.dot(com, cellmat)
        deltas = np.dot(deltas, cellmat)
        s += face(com, deltas)
    print(s)
    logger.info("Hook2: end.")
Exemplo n.º 3
0
def hook4(lattice):
    lattice.logger.info(
        "Hook4: A. Output depolarization process in Yaplot format.")
    print(lattice.yapresult, end="")
    lattice.logger.info("Hook4: B. Polyhedral expression.")
    # copied from svg_poly
    graph = nx.Graph(lattice.spacegraph)  #undirected
    cellmat = lattice.repcell.mat
    for ring in cr.CountRings(graph).rings_iter(8):
        deltas = np.zeros((len(ring), 3))
        d2 = np.zeros(3)
        for k, i in enumerate(ring):
            d = lattice.reppositions[i] - lattice.reppositions[ring[0]]
            d -= np.floor(d + 0.5)
            deltas[k] = d
            dd = lattice.reppositions[ring[k]] - lattice.reppositions[ring[k -
                                                                           1]]
            dd -= np.floor(dd + 0.5)
            d2 += dd
        # d2 must be zeros
        if np.all(np.absolute(d2) < 1e-5):
            comofs = np.sum(deltas, axis=0) / len(ring)
            deltas -= comofs
            com = lattice.reppositions[ring[0]] + comofs
            com -= np.floor(com)
            # rel to abs
            com = np.dot(com, cellmat)
            deltas = np.dot(deltas, cellmat)
            print(face(com, deltas), end="")
    print()
    lattice.logger.info("Hook4: end.")
Exemplo n.º 4
0
def hook4(lattice):
    lattice.logger.info("Hook4: Ring test.")
    graph = nx.Graph(lattice.spacegraph)  #undirected
    stat = dict()
    prob = defaultdict(int)
    for n in 3, 4, 5, 6, 7, 8:
        prob[n] = probabilities(n)
        stat[n] = defaultdict(int)
    for ring in cr.CountRings(graph).rings_iter(8):
        ori = orientations(ring, lattice.spacegraph)
        c = encode(ori)
        n = len(ring)
        stat[n][c] += 1
    #size code code(binary) Approx. Stat.
    for n in 3, 4, 5, 6, 7, 8:
        fmtstr = "{{0}} {{1}} {{1:0{0}b}} {{2}} {{3:.5f}} {{4:.5f}}".format(n)
        denom = 0
        for c in stat[n]:
            denom += stat[n][c]
        if denom > 0:
            dKL = 0.0
            for c in prob[n]:
                print(
                    fmtstr.format(n, c, prob[n][c], float(prob[n][c]),
                                  stat[n][c] / denom))
                q = stat[n][c] / denom
                p = prob[n][c]
                if q > 0.0:
                    dKL += q * (log(q) - log(p))
            dKL /= log(2.0)  #bit
            print("{1} {0} dKL[{0}-ring]".format(n, dKL))
            lattice.logger.info("  dKL[{0}-ring]={1}".format(n, dKL))
    #print(score)
    lattice.logger.info("Hook4: end.")
Exemplo n.º 5
0
def hook4(lattice):
    lattice.logger.info("Hook4: VPython (polyhedral expressions).")
    graph = nx.Graph(lattice.spacegraph)  #undirected
    cellmat = lattice.repcell.mat
    lattice.vpobjects = defaultdict(set)
    for ring in cr.CountRings(graph).rings_iter(8):
        deltas = np.zeros((len(ring), 3))
        d2 = np.zeros(3)
        for k, i in enumerate(ring):
            d = lattice.reppositions[i] - lattice.reppositions[ring[0]]
            d -= np.floor(d + 0.5)
            deltas[k] = d
            dd = lattice.reppositions[ring[k]] - lattice.reppositions[ring[k -
                                                                           1]]
            dd -= np.floor(dd + 0.5)
            d2 += dd
        # d2 must be zeros
        if np.all(np.absolute(d2) < 1e-5):
            comofs = np.sum(deltas, axis=0) / len(ring)
            deltas -= comofs
            com = lattice.reppositions[ring[0]] + comofs
            com -= np.floor(com)
            # rel to abs
            com = np.dot(com - 0.5, cellmat)
            deltas = np.dot(deltas, cellmat)
            ringsize = '{0}'.format(len(ring))
            lattice.vpobjects[ringsize] |= face(com, deltas)
    lattice.logger.info("Hook4: end.")
Exemplo n.º 6
0
def main():
    options = getoptions()
    if options.debug:
        logging.basicConfig(level=logging.DEBUG,
                            format="%(asctime)s %(levelname)s %(message)s")
    elif options.quiet:
        logging.basicConfig(level=logging.WARN,
                            format="%(asctime)s %(levelname)s %(message)s")
    else:
        #normal
        logging.basicConfig(level=logging.INFO,
                            format="%(asctime)s %(levelname)s %(message)s")
    logger = logging.getLogger()
    logger.debug("Debug mode.")
    logger.debug("Max size: {0}".format(options.maxsize))
    logger.debug("Stat only: {0}".format(options.countonly))

    file = sys.stdin
    while True:
        line = file.readline()
        if not line:
            break
        if line[0:5] == "@NGPH":
            (nmol, network) = cr.readNGPH(file)
            #print shortest_path(network, 0,3)
            ri = cr.CountRings(network).rings_iter(options.maxsize)
            if options.countonly:
                count = [0] * (options.maxsize - 2)
                for ring in ri:
                    count[len(ring) - 3] += 1
                print(" ".join([str(x) for x in count]))
            else:
                print(cr.saveRNGS(nmol, ri), end="")
Exemplo n.º 7
0
def hook4(lattice):
    lattice.logger.info("Hook4: Statistics on the HBs along a ring.")
    graph = nx.Graph(lattice.spacegraph) #undirected
    stat = dict()
    prob = defaultdict(int)

    # Ideal distributions
    for n in range(3, lattice.largestring+1):
        prob[n] = probabilities(n)
        stat[n] = defaultdict(int)

    for ring in cr.CountRings(graph, pos=lattice.reppositions).rings_iter(lattice.largestring):
        ori = orientations(ring, lattice.spacegraph)
        c   = encode(ori)
        n   = len(ring)
        stat[n][c] += 1

    #size code code(binary) Approx. Stat.
    lattice.logger.info("""
    _ringstat plugin makes the statistics of bond orientations along each
    HB ring and compare the distribution with that of an ideal (isolated
    random) ring. The difference in the distribution is evaluated by
    Kullback-Leibler # divergence, d_{KL}.
    A typical dKL is zero for hydrogen-disordered ices, while it is
    larger than 1 for hydrogen-ordered ones like ices 2 and 9.

    Ringstat analysis validates the ring-scale randomness. GenIce tool
    also certifies the zero net dipole moment and Bernal-Fowler-Pauling
    ice rule in terms of the validity in global and local structures.

    Columns in the output:
      ring size
      code (decimal) indicating the orientations of the bonds.
      code (binary)
      expectation (fractional) for an isolated random ring
      expectation (numerical)
      observation (fractional) in the given structure
      observation (numerical)

    dKL between expectiations and observations is also calculated.
    """)
    for n in range(3, lattice.largestring+1):
        fmtstr = "{{0}} {{1}} {{1:0{0}b}} {{2}} {{3:.5f}} {{5}}/{{6}} {{4:.5f}} ".format(n)
        denom = 0
        for c in stat[n]:
            denom += stat[n][c]
        if denom > 0:
            dKL = 0.0
            for c in prob[n]:
                print(fmtstr.format(n,c,prob[n][c], float(prob[n][c]), stat[n][c]/denom, stat[n][c], denom))
                q = stat[n][c]/denom
                p = prob[n][c]
                if q > 0.0:
                    dKL += q*(log(q) - log(p))
            dKL /= log(2.0)  #bit
            print("{1} {0} dKL[{0}-ring]".format(n,dKL))
            lattice.logger.info("  dKL[{0}-ring]={1}".format(n,dKL))
    #print(score)
    lattice.logger.info("Hook4: end.")
Exemplo n.º 8
0
def prepare(g, coord, maxring=7):
    """
    Make ring owner list
    """
    def ring_to_edge(ring):
        for i in range(len(ring)):
            yield ring[i - 1], ring[i]

    rings = []
    subgraphs = defaultdict(nx.Graph)
    rings_at = defaultdict(set)
    for ring in cr.CountRings(g).rings_iter(maxring):
        # make a ring list
        assert not is_spanning(ring, coord), "Some ring is spanning the cell."
        rings.append(ring)
        ringid = len(rings) - 1
        for node in ring:
            rings_at[node].add(ringid)
        for node in ring:
            # make a graph made of rings owned by the node
            for edge in ring_to_edge(ring):
                subgraphs[node].add_edge(*edge)
    return rings, subgraphs, rings_at
Exemplo n.º 9
0
def hook2(lattice):
    global options

    logger = getLogger()
    logger.info("Hook2: Cages and vitrites")

    cell = lattice.repcell.mat
    positions = lattice.reppositions
    graph = nx.Graph(lattice.graph)  #undirected
    ringsize = options.ring
    ringlist = [[
        int(x) for x in ring
    ] for ring in cr.CountRings(graph, pos=positions).rings_iter(max(ringsize))
                ]
    ringpos = [centerOfMass(ringnodes, positions) for ringnodes in ringlist]
    logger.info("  Rings: {0}".format(len(ringlist)))
    maxcagesize = max(options.sizes)
    cages = []
    for cage in Polyhed(ringlist, maxcagesize):
        if len(cage) in options.sizes:
            valid = True
            for ringid in cage:
                if len(ringlist[ringid]) not in ringsize:
                    valid = False
            if valid:
                cages.append(list(cage))
    logger.info("  Cages: {0}".format(len(cages)))
    cagepos = np.array([centerOfMass(cage, ringpos) for cage in cages])
    if options.gromacs:
        options.rings = ringlist
        options.cages = cages
        logger.debug("##2 {0}".format(cages))
        logger.info("Hook2: end.")
        return

    if options.quad:
        oncage = defaultdict(list)
        for cage in cages:
            nodes = set()
            for ringid in cage:
                nodes |= set(ringlist[ringid])
            for node in nodes:
                oncage[node].append(len(cage))
        op = dict()
        for node in oncage:
            count = [0 for i in range(17)]
            for v in oncage[node]:
                count[v] += 1
            v = "{0}{1}{2}{3}".format(count[12], count[14], count[15],
                                      count[16])
            op[node] = v

        stat = defaultdict(int)
        for node in sorted(op):
            v = op[node]
            stat[v] += 1

        if options.json:
            output = dict()
            N = positions.shape[0]
            output["op"] = {str(k): v for k, v in op.items()}
            output["stat"] = {k: v / N for k, v in stat.items()}
            print(json.dumps(output, indent=2, sort_keys=True))
        else:
            for node in sorted(op):
                print(node, op[node])
            print("# Statistics")
            for v in sorted(stat):
                print("{0} {1} {2}/{3}".format(v, stat[v] / positions.shape[0],
                                               stat[v], positions.shape[0]))
        #ideal = {"CS2": {"2002": 0.7058823529411765,
        #                 "3001": 0.23529411764705882,
        #                 "4000": 0.058823529411764705},
        #         "CS1": {"0400": 0.13043478260869565,
        #                 "1300": 0.8695652173913043},
        #}
        #for ref in ideal:
        #    dKL = 0
        #    for v in sorted(stat):
        #        if v in ideal[ref]:
        #            dKL += ideal[ref][v]*(log2(ideal[ref][v]) - log2(stat[v]/positions.shape[0]))
        #    print("{0} dKL={1}".format(ref, dKL))
    elif options.json:
        output = dict()
        output["rings"] = ringlist
        output["cages"] = cages
        output["ringpos"] = [[x, y, z] for x, y, z in ringpos]
        output["cagepos"] = [[x, y, z] for x, y, z in cagepos]
        print(json.dumps(output, indent=2, sort_keys=True))
    elif options.yaplot:
        s = ""
        for c, cage in enumerate(cages):
            nodes = dict()
            cagesize = len(cage)
            for ringid in cage:
                ns = ringlist[ringid]
                for node in ns:
                    if node not in nodes:
                        # relative pos of the node
                        nodepos = positions[node] - cagepos[c]
                        nodepos -= np.floor(nodepos + 0.5)
                        # shrink a little
                        nodes[node] = nodepos * 0.9
                s += yp.Color(len(ns))
                s += yp.Layer(cagesize)
                polygon = (np.array([nodes[node]
                                     for node in ns]) + cagepos[c]) @ cell
                s += yp.Polygon(polygon)
        print(s + "\n")
    elif options.python:
        import graphstat as gs
        db = gs.GraphStat()
        labels = set()
        g_id2label = dict()
        print('cages="""')
        for c, cage in enumerate(cages):
            g = cage_to_graph(cage, ringlist)
            cagesize = len(cage)
            g_id = db.query_id(g)
            if g_id < 0:
                g_id = db.register()
                enum = 0
                label = "{0}".format(cagesize, enum)
                while label in labels:
                    enum += 1
                    label = "{0}_{1}".format(cagesize, enum)
                g_id2label[g_id] = label
                labels.add(label)
            else:
                label = g_id2label[g_id]
            print("{0:10s} {1:.4f} {2:.4f} {3:.4f}".format(label, *cagepos[c]))
        print('"""')
    else:
        # human-friendly redundant format
        for cageid, cage in enumerate(cages):
            print("Cage {0}: ({1}, {2}, {3}) {4} hedron".format(
                cageid, *cagepos[cageid], len(cage)))
            for ringid in sorted(cage):
                print("  Ring {0}: ({1}, {2}, {3}) {4} gon".format(
                    ringid, *ringpos[ringid], len(ringlist[ringid])))
                print("    Nodes: {0}".format(ringlist[ringid]))
    logger.info("Hook2: end.")
    return True  # terminate