def dump_reference_json():
    sys.path.insert(0, os.path.join(root, "build/"))
    sys.path.insert(0, os.path.join(root, "tests/"))
    mp.dps = 200
    data = []
    for l in range(20):
        for n in range(20):
            # z > 660 will lead to larger than double::max() values for a > 19
            for z in [
                    1e-2,
                    1e-1,
                    1,
                    10,
                    20,
                    30,
                    40,
                    60,
                    80,
                    100,
                    150,
                    200,
                    500,
                    660,
            ]:
                a = 0.5 * (n + l + 3)
                b = l + 1.5

                val = float(hyp1f1(a, b, z))
                der = float(a / b * hyp1f1(a + 1, b + 1, z))
                data.append(dict(a=a, b=b, z=z, val=val, der=der))
    print(len(data))
    with open(os.path.join(root, dump_path, "hyp1f1_reference.ubjson"),
              "wb") as f:
        ubjson.dump(data, f)
示例#2
0
def trigger_action(data):
    """packs and writes"""
    nant, de = get_delays()
    t0, t1, sn, dm, width, pt, s = struct.unpack('ddffff128s', data)
    print("Triggered on DM={0:3.2f} S/N={1:2.1f} width={4:2.1f} I0={2}".format(
        dm, sn, t0, time.time(), 1e3 * width))
    slack_push(
        "ML triggered on DM={0:3.2f} S/N={1:2.1f} width={4:2.1f} I0={2}".
        format(dm, sn, t0, time.time(), 1e3 * width))
    ##
    ret = dict()
    ret['sn'] = sn
    ret['dm'] = dm
    ret['width'] = width
    ret['peak_time'] = pt
    ret['t0'] = t0
    ret['t1'] = t1
    ret['meta'] = s
    #ret['nant']       = nant
    ret['delays'] = de
    ret['antprops'] = ANTPROP
    ##
    i0 = int(t0)
    d0 = int(t1 - t0)
    fn = "{0}_i{1}_dm{2:05.2f}_sn{3:05.2f}_wd{4:05.2f}.meta".format(
        i0, d0, dm, sn, width * 1e3)
    with open(os.path.join(METADIR, fn), 'wb') as f:
        ubjson.dump(ret, f)
def dump_reference_json():
    path = '../'
    sys.path.insert(0, os.path.join(path, 'build/'))
    sys.path.insert(0, os.path.join(path, 'tests/'))
    data = []
    a = 0
    for order in range(2,20):
        for b in np.linspace(2,10,20):
            x,w = get_leggauss(order, a, b)
            data.append(dict(a=a,b=b,order=order,points=x.tolist(),weights=w.tolist()))
    print(len(data))
    with open(path+"tests/reference_data/gauss_legendre_reference.ubjson",'wb') as f:
        ubjson.dump(data,f)
def dump_reference_json():
    sys.path.insert(0, os.path.join(root, "build/"))
    sys.path.insert(0, os.path.join(root, "tests/"))
    data = dict(i_complete_square=[])
    # 1 test the special case in the bessel function and 20 test that we
    # can ramp up l_max safely
    max_orders = [1, 20]
    for max_order in max_orders:
        orders = list(range(max_order))
        # gaussian sigma in [0.1, 0.9]
        alphas = np.linspace(0.6, 50, 10)
        # looks at rc up to 10
        xns = np.linspace(0.005, 10, 15)
        # to test values around the bessel tolerance
        xns = np.hstack((1e-6, 1e-5, xns))
        # atoms should not be much closer than this
        rijs = np.linspace(0.5, 10, 15)
        # to test values around the bessel tolerance
        rijs = np.hstack((1e-6, 1e-5, rijs))

        for alpha in alphas:
            for rij in rijs:
                vals = []
                for xn in xns:
                    vals.append([])
                    for order in orders:
                        val = sbesseli_complete_square(order, alpha, rij, xn)
                        vals[-1].append(val)
                # avoid values that are too small for ubjson to be interpreted
                # as doubles
                vals = np.array(vals)
                vals[vals < 1e-300] = 0.0
                data["i_complete_square"].append(
                    dict(
                        alpha=alpha,
                        rij=rij,
                        xs=xns.tolist(),
                        max_order=max_order,
                        vals=vals.tolist(),
                    ))

    with open(
            os.path.join(root, dump_path,
                         "modified_bessel_first_kind_reference.ubjson"),
            "wb",
    ) as f:
        ubjson.dump(data, f)
示例#5
0
def saveb(data, fname, opt={}, **kwargs):
    """@brief Saving a Python data structure to a binary JData (UBJSON) file

    @param[in] data: data to be saved
    @param[in] fname: a binary (UBJSON based) JData file name
    @param[in] opt: options, if opt['encode']=True or 1 (default), call jdata.encode() before saving
    """
    opt.setdefault('encode',True)

    try:
        import ubjson
    except ImportError:
        raise ImportError('To read/write binary JData files, you must install the py-ubjson module by "pip install py-ubjson"')
    else:
        if(opt['encode']):
            data=jd.encode(data,opt);
        with open(fname, "w") as fid:
            ubjson.dump(data, fid,**kwargs);
def dump_reference_json():
    path = '../'
    sys.path.insert(0, os.path.join(path, 'build/'))
    sys.path.insert(0, os.path.join(path, 'tests/'))
    mp.dps = 200
    data = []
    for l in range(20):
        for n in range(20):
            for z in [1e-2, 1e-1, 1, 10, 20, 30, 40, 60, 80, 100, 150, 200]:
                a = 0.5 * (n + l + 3)
                b = l + 1.5

                val = float(hyp1f1(a, b, z))
                der = float(a / b * hyp1f1(a + 1, b + 1, z))
                data.append(dict(a=a, b=b, z=z, val=val, der=der))
    print(len(data))
    with open(path + "tests/reference_data/hyp1f1_reference.ubjson",
              'wb') as f:
        ubjson.dump(data, f)
示例#7
0
def dump_reference_json():
    sys.path.insert(0, os.path.join(root, "build/"))
    sys.path.insert(0, os.path.join(root, "tests/"))
    data = []
    a = 0
    for order in range(2, 20):
        for b in np.linspace(2, 10, 20):
            x, w = get_leggauss(order, a, b)
            data.append(
                dict(
                    a=a,
                    b=b,
                    order=order,
                    points=x.tolist(),
                    weights=w.tolist(),
                ))
    print(len(data))
    with open(os.path.join(root, dump_path, "gauss_legendre_reference.ubjson"),
              "wb") as f:
        ubjson.dump(data, f)
示例#8
0
def tofile(fn, frames):
    import numpy as np
    keys = ['positions', 'cell', 'numbers', 'pbc']
    data = {}
    for ii, frame in zip(range(1, len(frames) + 1), frames):
        aa = dict(positions=frame.get_positions().tolist(),
                  cell=frame.get_cell().tolist(),
                  numbers=frame.get_atomic_numbers().tolist(),
                  pbc=frame.get_pbc().tolist())
        aa['info'] = {}
        for k, v in frame.info.items():
            if isinstance(v, np.integer):
                aa['info'][k] = int(v)
            elif isinstance(v, np.bool_):
                aa['info'][k] = bool(v)
            elif isinstance(v, np.float):
                aa['info'][k] = float(v)
            elif hasattr(v, 'tolist'):
                aa['info'][k] = v.tolist()
            else:
                aa['info'][k] = v
        aa['arrays'] = {}
        for k, v in frame.arrays.items():
            if k not in keys:
                aa['arrays'][k] = v.tolist()
        data[str(ii)] = aa
    data['ids'] = list(range(1, len(frames) + 1))
    data['nextid'] = len(frames) + 1
    _, extension = os.path.splitext(fn)
    if extension == '.json':
        with open(fn, 'w') as f:
            # json.dump(data, f)
            data_pretty = prettyjson(data, indent=2, maxlinelength=80)
            f.write(data_pretty)
    elif extension == '.ubjson':
        with open(fn, 'wb') as f:
            ubjson.dump(data, f, no_float32=False)
示例#9
0
def dump_reference_json():
    import ubjson
    import os
    from copy import copy
    from itertools import product
    path = '../'
    sys.path.insert(0, os.path.join(path, 'build/'))
    sys.path.insert(0, os.path.join(path, 'tests/'))

    cutoffs = [3]
    gaussian_sigmas = [0.4]
    max_radials = [1, 2, 3]
    max_angulars = [1, 2, 4]
    soap_types = ["LambdaSpectrum"]
    inversion_symmetries = [True, False]

    Lambdas = [1]
    fns = [
        os.path.join(
            path, "tests/reference_data/CaCrP2O7_mvc-11955_symmetrized.json"),
        os.path.join(path, "tests/reference_data/small_molecule.json")
    ]
    fns_to_write = [
        "reference_data/CaCrP2O7_mvc-11955_symmetrized.json",
        "reference_data/small_molecule.json",
    ]

    data = dict(filenames=fns_to_write,
                cutoffs=cutoffs,
                gaussian_sigmas=gaussian_sigmas,
                max_radials=max_radials,
                soap_types=soap_types,
                rep_info=[])

    for fn in fns:
        frames = read(fn)
        for cutoff in cutoffs:
            print(fn, cutoff)
            data['rep_info'].append([])
            for (soap_type, gaussian_sigma, max_radial,
                 max_angular, inversion_symmetry, Lambda) in product(
                    soap_types, gaussian_sigmas, max_radials, max_angulars,
                    inversion_symmetries, Lambdas):
                hypers = {"interaction_cutoff": cutoff,
                          "cutoff_smooth_width": 0.5,
                          "max_radial": max_radial,
                          "max_angular": max_angular,
                          "gaussian_sigma_type": "Constant",
                          "gaussian_sigma_constant": gaussian_sigma,
                          "cutoff_function_type": "ShiftedCosine",
                          "radial_basis": "GTO",
                          "normalize": True,
                          "soap_type": soap_type,
                          "inversion_symmetry": inversion_symmetry,
                          "lam": Lambda}
                soap = SphericalCovariants(**hypers)
                soap_vectors = soap.transform(frames)
                x = soap_vectors.get_features(soap)
                x[np.abs(x) < 1e-300] = 0.
                data['rep_info'][-1].append(dict(feature_matrix=x.tolist(),
                                                 hypers=copy(soap.hypers)))

    with open(path +
              "tests/reference_data/spherical_covariants_reference.ubjson",
              'wb') as f:
        ubjson.dump(data, f)
示例#10
0
def dump_reference_json():
    import ubjson
    from copy import copy
    from itertools import product

    sys.path.insert(0, os.path.join(root, 'build/'))
    sys.path.insert(0, os.path.join(root, 'tests/'))

    cutoffs = [2, 3]
    gaussian_sigmas = [0.2, 0.5]
    max_radials = [4, 10]
    max_angulars = [3, 6]
    soap_types = ["RadialSpectrum", "PowerSpectrum", "BiSpectrum"]
    inversion_symmetry = False
    radial_basis = ["GTO"]

    fns = [
        os.path.join(inputs_path, "CaCrP2O7_mvc-11955_symmetrized.json"),
        os.path.join(inputs_path, "small_molecule.json")
    ]
    fns_to_write = [
        os.path.join(dump_path, "CaCrP2O7_mvc-11955_symmetrized.json"),
        os.path.join(dump_path, "small_molecule.json"),
    ]

    data = dict(filenames=fns_to_write,
                cutoffs=cutoffs,
                gaussian_sigmas=gaussian_sigmas,
                max_radials=max_radials,
                soap_types=soap_types,
                rep_info=[])

    for fn in fns:
        frames = read(fn)
        for cutoff in cutoffs:
            print(fn, cutoff)
            data['rep_info'].append([])
            for (soap_type, gaussian_sigma, max_radial, max_angular,
                 rad_basis) in product(soap_types, gaussian_sigmas,
                                       max_radials, max_angulars,
                                       radial_basis):
                if 'RadialSpectrum' == soap_type:
                    max_angular = 0
                if "BiSpectrum" == soap_type:
                    max_radial = 2
                    max_angular = 1
                    inversion_symmetry = True

                hypers = {
                    "interaction_cutoff": cutoff,
                    "cutoff_smooth_width": 0.5,
                    "max_radial": max_radial,
                    "max_angular": max_angular,
                    "gaussian_sigma_type": "Constant",
                    "normalize": True,
                    "cutoff_function_type": "ShiftedCosine",
                    "radial_basis": rad_basis,
                    "gaussian_sigma_constant": gaussian_sigma,
                    "soap_type": soap_type,
                    "inversion_symmetry": inversion_symmetry,
                }

                soap = SphericalInvariants(**hypers)
                soap_vectors = soap.transform(frames)
                x = soap_vectors.get_features(soap)
                x[np.abs(x) < 1e-300] = 0.
                data['rep_info'][-1].append(
                    dict(feature_matrix=x.tolist(), hypers=copy(soap.hypers)))

    with open(
            os.path.join(root, dump_path,
                         "spherical_invariants_reference.ubjson"), 'wb') as f:
        ubjson.dump(data, f)
示例#11
0
def write_dbson(fname, obj):
    """
    Writes dbson. 
    """
    with open(fname, "wb") as f:
        ubjson.dump(from_dbson(obj), f)
示例#12
0
    "reference_data/CaCrP2O7_mvc-11955_symmetrized.json",
    "reference_data/small_molecule.json"
]

data = dict(filenames=fns_to_write, cutoffs=cutoffs, rep_info=[])
hypers = dict(central_decay=-1,
              interaction_cutoff=-1,
              interaction_decay=-1,
              size=10,
              sorting_algorithm='')

for fn in fns:
    for cutoff in cutoffs:
        print(fn, cutoff)
        data['rep_info'].append([])
        for sort in sorts:
            rep = SortedCoulombMatrix(cutoff, sorting_algorithm=sort)
            frame = [json2ase(load_json(fn))]
            features = rep.transform(frame)
            test = features.get_feature_matrix()
            hypers['size'] = rep.size
            print(rep.size)
            hypers['sorting_algorithm'] = sort
            data['rep_info'][-1].append(
                dict(feature_matrix=test.tolist(), hypers=copy(hypers)))

with open(
        os.path.join(path, "tests", "reference_data",
                     "sorted_coulomb_reference.ubjson"), 'wb') as f:
    ubjson.dump(data, f)
示例#13
0
文件: learn.py 项目: satojk/fishnet
def serialize_data(src, data):
    with gzip.open(src, "wb") as f:
        ubjson.dump(data, f)
def dump_reference_json():
    import ubjson
    import os
    from copy import copy
    path = '../'
    sys.path.insert(0, os.path.join(path, 'build/'))
    sys.path.insert(0, os.path.join(path, 'tests/'))

    cutoffs = [2, 3]
    gaussian_sigmas = [0.2, 0.5]
    max_radials = [4, 10]
    max_angulars = [3, 6]
    soap_types = ["RadialSpectrum", "PowerSpectrum", "BiSpectrum"]
    inversion_symmetry = False

    fns = [
        os.path.join(
            path, "tests/reference_data/CaCrP2O7_mvc-11955_symmetrized.json"),
        os.path.join(path, "tests/reference_data/small_molecule.json")
    ]
    fns_to_write = [
        "reference_data/CaCrP2O7_mvc-11955_symmetrized.json",
        "reference_data/small_molecule.json",
    ]

    data = dict(filenames=fns_to_write,
                cutoffs=cutoffs,
                gaussian_sigmas=gaussian_sigmas,
                max_radials=max_radials,
                soap_types=soap_types,
                rep_info=[])

    for fn in fns:
        frames = [json2ase(load_json(fn))]
        for cutoff in cutoffs:
            print(fn, cutoff)
            data['rep_info'].append([])
            for soap_type in soap_types:
                for gaussian_sigma in gaussian_sigmas:
                    for max_radial in max_radials:
                        for max_angular in max_angulars:
                            if 'RadialSpectrum' == soap_type:
                                max_angular = 0
                            if "BiSpectrum" == soap_type:
                                max_radial = 2
                                max_angular = 1
                                inversion_symmetry = True

                            hypers = {
                                "interaction_cutoff": cutoff,
                                "cutoff_smooth_width": 0.5,
                                "max_radial": max_radial,
                                "max_angular": max_angular,
                                "gaussian_sigma_type": "Constant",
                                "normalize": True,
                                "cutoff_function_type": "Cosine",
                                "radial_basis": "GTO",
                                "gaussian_sigma_constant": gaussian_sigma,
                                "soap_type": soap_type,
                                "inversion_symmetry": inversion_symmetry,
                            }

                            soap = SphericalInvariants(**hypers)
                            soap_vectors = soap.transform(frames)
                            x = soap_vectors.get_feature_matrix()
                            # x = get_feature_vector(hypers, frames)
                            data['rep_info'][-1].append(
                                dict(feature_matrix=x.tolist(),
                                     hypers=copy(soap.hypers)))

    with open(
            path +
            "tests/reference_data/spherical_invariants_reference.ubjson",
            'wb') as f:
        ubjson.dump(data, f)
示例#15
0
文件: __init__.py 项目: musec/py-cdg
def save(graph, output, filename):
    nodes = graph.nodes
    roots = ((k, v) for (k, v) in graph.nodes.items() if 'parent' not in v)

    functions = collections.defaultdict(new_empty_function)
    for (fn_name, fn_attrs) in roots:
        if 'children' not in fn_attrs:
            continue

        fn = functions[fn_name]

        # Blocks have children; anything else must be an argument.
        child_names = set(fn_attrs['children'])
        blocks = {
            n
            for n in child_names if n in nodes  #and 'children' in nodes[n]
        }
        args = child_names.difference(blocks)

        for block_name in blocks:
            block_attrs = nodes[block_name]
            block = fn['blocks'][block_name] = dict([
                (k, v) for (k, v) in nodes[block_name].items()
                if k not in ('parent', 'children')
            ])

            for child_name in block_attrs['children']:
                child_attrs = nodes[child_name] if child_name in nodes else {}
                if 'parent' in child_attrs:
                    child_attrs.pop('parent')
                assert 'children' not in child_attrs

                block[child_name] = child_attrs

        for arg_name in args:
            #if arg_name not in nodes:
            #    continue

            arg_attrs = nodes[arg_name]
            arg_attrs.pop('parent')
            assert 'children' not in arg_attrs

            fn['arguments'][arg_name] = dict(arg_attrs)

        functions[fn_name] = fn

    for (src, dest, data) in graph.edges(data=True):
        #if src not in nodes or dest not in nodes:
        #    continue

        (fn_name, src_name) = src.split('::', 1)
        kind = data['kind']

        data = {
            'from': src,
            'to': dest,
            'kind': EdgeKind.to_str(kind),
        }

        if kind == EdgeKind.Call:
            functions[fn_name]['calls'].append(data)
        else:
            functions[fn_name]['flows'].append(data)

    if filename.endswith('.cdg'):
        import ubjson
        cg = ubjson.load(stream)

    elif filename.endswith('.json'):
        import json
        cg = json.load(stream)

    elif filename.endswith('.yaml'):
        import yaml

        try:
            from yaml import CLoader as Loader
        except ImportError:
            from yaml import Loader

        cg = yaml.load(stream, Loader=Loader)

    import ubjson
    ubjson.dump({'functions': functions}, output)
def dump_reference_json():
    import ubjson
    from copy import copy
    from itertools import product

    sys.path.insert(0, os.path.join(root, 'build/'))
    sys.path.insert(0, os.path.join(root, 'tests/'))

    cutoffs = [2, 3]
    gaussian_sigmas = [0.2, 0.5]
    max_radials = [4, 10]
    max_angulars = [3, 6]
    cutoff_smooth_widths = [0., 1.]
    radial_basis = ["GTO", "DVR"]
    cutoff_function_types = ['ShiftedCosine', 'RadialScaling']
    fns = [
        os.path.join(inputs_path, "CaCrP2O7_mvc-11955_symmetrized.json"),
        os.path.join(inputs_path, "small_molecule.json")
    ]
    fns_to_write = [
        os.path.join(dump_path, "CaCrP2O7_mvc-11955_symmetrized.json"),
        os.path.join(dump_path, "small_molecule.json"),
    ]

    data = dict(filenames=fns_to_write,
                cutoffs=cutoffs,
                gaussian_sigmas=gaussian_sigmas,
                max_radials=max_radials,
                rep_info=[])

    for fn in fns:
        for cutoff in cutoffs:
            data['rep_info'].append([])
            for (gaussian_sigma, max_radial, max_angular, cutoff_smooth_width,
                 rad_basis, cutoff_function_type) in product(
                     gaussian_sigmas, max_radials, max_angulars,
                     cutoff_smooth_widths, radial_basis,
                     cutoff_function_types):
                frames = read(fn)
                if cutoff_function_type == 'RadialScaling':
                    cutoff_function_parameters = dict(rate=1,
                                                      scale=cutoff * 0.5,
                                                      exponent=3)
                else:
                    cutoff_function_parameters = dict()

                hypers = {
                    "interaction_cutoff": cutoff,
                    "cutoff_smooth_width": cutoff_smooth_width,
                    "max_radial": max_radial,
                    "max_angular": max_angular,
                    "gaussian_sigma_type": "Constant",
                    "cutoff_function_type": cutoff_function_type,
                    'cutoff_function_parameters': cutoff_function_parameters,
                    "gaussian_sigma_constant": gaussian_sigma,
                    "radial_basis": rad_basis
                }

                sph_expn = SphericalExpansion(**hypers)
                expansions = sph_expn.transform(frames)
                x = expansions.get_features(sph_expn)
                x[np.abs(x) < 1e-300] = 0.
                data['rep_info'][-1].append(
                    dict(feature_matrix=x.tolist(),
                         hypers=copy(sph_expn.hypers)))

    with open(
            os.path.join(root, dump_path,
                         "spherical_expansion_reference.ubjson"), 'wb') as f:
        ubjson.dump(data, f)
def dump_reference_json():
    # to produces more readable tests use l_max 2 or 3
    verbose = False
    l_max = 30
    sys.path.insert(0, os.path.join(root, 'build/'))
    sys.path.insert(0, os.path.join(root, 'tests/'))
    data = []
    mp.dps = 200

    # Calculation of spherical harmonics
    # with mpmath:
    ## spherharm(angular_l,angular_m, theta, phi)
    # with scipy:
    ## sph_harm(angular_m, angular_l, phi, theta)

    unit_vectors = load_unit_vectors_from_json()

    # In arXiv 1410.1748 e.q. (4) the factors in front of the associated
    # polynomial
    alp_normfacts = np.zeros((l_max + 1, l_max + 1))
    for l in range(l_max + 1):
        for m in range(l + 1):

            alp_normfacts[l, m] = mpmath.sqrt(
                (2 * l + 1) / (2 * mpmath.pi) /
                reduce(lambda x, y: mpmath.fmul(x, y),
                       mpmath.arange(l - m + 1, l + m + 1), 1))
    if verbose:
        print("alp_normfacts")
        print(alp_normfacts)

    for unit_vector in unit_vectors:
        # Calculating the spherical harmonics

        harmonics = []
        # copy of c++ code:
        # double cos_theta = unit_vector[2];
        cos_theta = unit_vector[2]
        theta = np.arccos(cos_theta)
        # copy of c++ code:
        # double phi = std::atan2(unit_vector[1], unit_vector[0]);
        phi = np.arctan2(unit_vector[1], unit_vector[0])
        if verbose:
            print(unit_vector)
        for l in range(l_max + 1):

            # calculation for negative m
            for m in range(-l, 0):
                result = np.sqrt(2) * np.imag(
                    sph_harm(np.abs(m), l, phi, theta))
                harmonics.append(float(result))
                if verbose:
                    print(l, m, result)
            # calculation for m=0
            result = np.real(sph_harm(0, l, phi, theta))
            harmonics.append(float(result))
            if verbose:
                print(l, 0, result)
            # calculation for positive m
            for m in range(1, l + 1):
                result = np.sqrt(2) * np.real(sph_harm(m, l, phi, theta))
                harmonics.append(float(result))
                if verbose:
                    print(l, m, result)

        # Calculating the associated legendre polynomial

        # copy of c++ code:
        # double cos_theta = unit_vector[2];
        cos_theta = unit_vector[2]
        alps = lpmn(l_max, l_max, cos_theta)[0].T
        if verbose:
            print("lpmn")
            print(alps)
        alps *= alp_normfacts
        if verbose:
            print("alps")
            print(alps)
        alps = list(map(float, alps.reshape(-1).tolist()))
        data.append(
            dict(max_angular_l=int(l_max),
                 unit_vector=unit_vector,
                 harmonics=harmonics,
                 alps=alps))
    if verbose:
        print(len(data))
    with open(
            os.path.join(root, dump_path,
                         "spherical_harmonics_reference.ubjson"), 'wb') as f:
        ubjson.dump(data, f)
示例#18
0
def dump_reference_json():
    import ubjson
    import os
    from copy import copy
    path = '../'
    sys.path.insert(0, os.path.join(path, 'build/'))
    sys.path.insert(0, os.path.join(path, 'tests/'))

    cutoffs = [2, 3]
    gaussian_sigmas = [0.2, 0.5]
    max_radials = [4, 10]
    max_angulars = [3, 6]
    cutoff_smooth_widths = [0., 1.]
    radial_basis = ["GTO"]

    fns = [
        os.path.join(
            path, "tests/reference_data/CaCrP2O7_mvc-11955_symmetrized.json"),
        os.path.join(path, "tests/reference_data/small_molecule.json")
    ]
    fns_to_write = [
        "reference_data/CaCrP2O7_mvc-11955_symmetrized.json",
        "reference_data/small_molecule.json",
    ]

    data = dict(filenames=fns_to_write,
                cutoffs=cutoffs,
                gaussian_sigmas=gaussian_sigmas,
                max_radials=max_radials,
                rep_info=[])

    # An example of the gruesomeness of using 4 spaces for one tab
    for fn in fns:
        for cutoff in cutoffs:
            data['rep_info'].append([])
            for gaussian_sigma in gaussian_sigmas:
                for max_radial in max_radials:
                    for max_angular in max_angulars:
                        for cutoff_smooth_width in cutoff_smooth_widths:
                            for rad_basis in radial_basis:
                                frames = [json2ase(load_json(fn))]
                                hypers = {
                                    "interaction_cutoff": cutoff,
                                    "cutoff_smooth_width": cutoff_smooth_width,
                                    "max_radial": max_radial,
                                    "max_angular": max_angular,
                                    "gaussian_sigma_type": "Constant",
                                    "cutoff_function_type": "Cosine",
                                    "gaussian_sigma_constant": gaussian_sigma,
                                    "radial_basis": rad_basis
                                }
                                # x = get_soap_vectors(hypers, frames)
                                sph_expn = SphericalExpansion(**hypers)
                                expansions = sph_expn.transform(frames)
                                x = expansions.get_feature_matrix()
                                data['rep_info'][-1].append(
                                    dict(feature_matrix=x.tolist(),
                                         hypers=copy(sph_expn.hypers)))

    with open(
            path + "tests/reference_data/spherical_expansion_reference.ubjson",
            'wb') as f:
        ubjson.dump(data, f)
def dump_reference_json():
    import ubjson
    from copy import copy
    from itertools import product

    sys.path.insert(0, os.path.join(root, "build/"))
    sys.path.insert(0, os.path.join(root, "tests/"))

    cutoffs = [2, 3]
    gaussian_sigmas = [0.2, 0.5]
    max_radials = [4]
    max_angulars = [3]
    cutoff_smooth_widths = [1.0]
    radial_basis = ["GTO", "DVR"]
    cutoff_function_types = ["ShiftedCosine", "RadialScaling"]
    fns = [
        os.path.join(inputs_path, "CaCrP2O7_mvc-11955_symmetrized.json"),
        os.path.join(inputs_path, "small_molecule.json"),
    ]
    fns_to_write = [
        os.path.join(read_inputs_path, "CaCrP2O7_mvc-11955_symmetrized.json"),
        os.path.join(read_inputs_path, "small_molecule.json"),
    ]
    optimization_args = [
        {
            "type": "None",
            "accuracy": 1e-8
        },
        {
            "type": "Spline",
            "accuracy": 1e-8
        },
    ]
    data = dict(
        filenames=fns_to_write,
        cutoffs=cutoffs,
        gaussian_sigmas=gaussian_sigmas,
        max_radials=max_radials,
        rep_info=[],
    )

    for fn in fns:
        for cutoff in cutoffs:
            data["rep_info"].append([])
            for (
                    gaussian_sigma,
                    max_radial,
                    max_angular,
                    cutoff_smooth_width,
                    rad_basis,
                    cutoff_function_type,
                    opt_args,
            ) in product(
                    gaussian_sigmas,
                    max_radials,
                    max_angulars,
                    cutoff_smooth_widths,
                    radial_basis,
                    cutoff_function_types,
                    optimization_args,
            ):
                frames = read(fn)
                if cutoff_function_type == "RadialScaling":
                    cutoff_function_parameters = dict(rate=1,
                                                      scale=cutoff * 0.5,
                                                      exponent=3)
                else:
                    cutoff_function_parameters = dict()

                hypers = {
                    "interaction_cutoff": cutoff,
                    "cutoff_smooth_width": cutoff_smooth_width,
                    "max_radial": max_radial,
                    "max_angular": max_angular,
                    "gaussian_sigma_type": "Constant",
                    "cutoff_function_type": cutoff_function_type,
                    "cutoff_function_parameters": cutoff_function_parameters,
                    "gaussian_sigma_constant": gaussian_sigma,
                    "radial_basis": rad_basis,
                    "optimization_args": opt_args,
                }

                sph_expn = SphericalExpansion(**hypers)
                expansions = sph_expn.transform(frames)
                x = expansions.get_features(sph_expn)
                x[np.abs(x) < 1e-300] = 0.0
                data["rep_info"][-1].append(
                    dict(feature_matrix=x.tolist(),
                         hypers=copy(sph_expn.hypers)))

    with open(
            os.path.join(root, dump_path,
                         "spherical_expansion_reference.ubjson"),
            "wb",
    ) as f:
        ubjson.dump(data, f)
示例#20
0
def dump_reference_json():
    import ubjson
    import os
    from copy import copy
    sys.path.insert(0, os.path.join(root, 'build/'))
    sys.path.insert(0, os.path.join(root, 'tests/'))

    cutoffs = [3.5]
    gaussian_sigmas = [0.5]
    max_radials = [6]
    max_angulars = [6]
    soap_types = ["RadialSpectrum", "PowerSpectrum"]

    fn = os.path.join(inputs_path, "small_molecules-20.json")
    fn_to_write = os.path.join(
        'reference_data', "inputs", "small_molecules-20.json")
    start = 0
    length = 5
    representations = ['spherical_invariants']
    kernel_names = ['Cosine']
    target_types = ['Structure', 'Atom']
    dependant_args = dict(Cosine=[dict(zeta=1), dict(zeta=2), dict(zeta=4)])

    data = dict(filename=fn_to_write,
                start=start,
                length=length,
                cutoffs=cutoffs,
                gaussian_sigmas=gaussian_sigmas,
                max_radials=max_radials,
                soap_types=soap_types,
                kernel_names=kernel_names,
                target_types=target_types,
                dependant_args=dependant_args,
                rep_info=dict(spherical_invariants=[]))

    frames = read(fn, '{}:{}'.format(start, start + length))
    for representation_name in representations:
        for cutoff in cutoffs:
            print(fn, cutoff)
            data['rep_info'][representation_name].append([])
            for kernel_name in kernel_names:
                for target_type in target_types:
                    for kwargs in dependant_args[kernel_name]:
                        for soap_type in soap_types:
                            for gaussian_sigma in gaussian_sigmas:
                                for max_radial in max_radials:
                                    for max_angular in max_angulars:
                                        if 'RadialSpectrum' == soap_type:
                                            max_angular = 0

                                        hypers = {"interaction_cutoff": cutoff,
                                                  "cutoff_smooth_width": 0.5,
                                                  "max_radial": max_radial,
                                                  "max_angular": max_angular,
                                                  "gaussian_sigma_type": "Constant",
                                                  "gaussian_sigma_constant": gaussian_sigma,
                                                  "soap_type": soap_type,
                                                  "cutoff_function_type": "ShiftedCosine",
                                                  "normalize": True,
                                                  "radial_basis": "GTO"}
                                        soap = SphericalInvariants(**hypers)
                                        soap_vectors = soap.transform(frames)
                                        hypers_kernel = dict(name=kernel_name,
                                                             target_type=target_type)
                                        hypers_kernel.update(**kwargs)
                                        kernel = Kernel(soap, **hypers_kernel)
                                        kk = kernel(soap_vectors)
                                        # x = get_spectrum(hypers, frames)
                                        for aa in soap.nl_options:
                                            aa['initialization_arguments'] = aa['args']

                                        data['rep_info'][representation_name][-1].append(dict(kernel_matrix=kk.tolist(),
                                                                                              hypers_rep=copy(
                                                                                                  soap.hypers),
                                                                                              hypers_manager=copy(
                                                                                                  soap.nl_options),
                                                                                              hypers_kernel=copy(hypers_kernel)))

    with open(os.path.join(root, dump_path,
                           "kernel_reference.ubjson"), 'wb') as f:
        ubjson.dump(data, f)