示例#1
0
def test_cli_route_prefix_table():
    kern = kernel.Kernel(log=None, log_id="", table_name="main")
    if not kern.platform_supported:
        return
    # We assume that the main route table always has a default route, and we look for this:
    # +--------------------------+------------------+
    # | Table                    | Main             |
    # | Address Family           | IPv4             |
    # | Destination              | 0.0.0.0/0        |
    # | Type                     | Unicast          |
    # | Protocol                 | Boot             | << or Dhcp in some deployments
    # | Scope                    | Universe         |
    # | Next-hops                | eth0 172.17.0.1  |
    # | Priority                 |                  |
    # | Preference               |                  |
    # | Preferred Source Address |                  |
    # | Source                   |                  |
    # | Flow                     |                  |
    # | Encapsulation Type       |                  |
    # | Encapsulation            |                  |
    # | Metrics                  |                  |
    # | Type of Service          | 0                |
    # | Flags                    | 0                |
    # +--------------------------+------------------+
    default_prefix = packet_common.make_ip_prefix("0.0.0.0/0")
    tab_str = kern.cli_route_prefix_table(254, default_prefix).to_string()
    pattern = (r"[|] Table +[|] Main +[|]\n"
               r"[|] Address Family +[|] IPv4 +[|]\n"
               r"[|] Destination +[|] 0\.0\.0\.0/0 +[|]\n"
               r"[|] Type +[|] Unicast +[|]\n"
               r"[|] Protocol +[|] (Boot|Dhcp) +[|]\n"
               r"[|] Scope +[|] Universe +[|]\n")
    assert re.search(pattern, tab_str) is not None
示例#2
0
    def test_gaussian_energy_matrix_values(self):
        kern = kernel.Kernel('gaussian', 1)
        expected_val = np.ones((10, 10)) * exp(-1)
        np.fill_diagonal(expected_val, 1)

        exp_eye = kern.kernel_mat(np.eye(10), np.eye(10))
        self.assertTrue(np.array_equal(exp_eye, expected_val))
示例#3
0
    def testKernel(self):
        testfile_path = os.path.dirname(__file__)
        test_skeleton = skeleton.Skeleton()
        test_skeleton.Load(
            os.path.join(testfile_path, "simple_skeleton.pb.txt"))
        s1 = np.zeros((2, 4, 4, 2), dtype=np.float32)
        s1[0, :, :, 0] = [[1.0, 0, 1, 1], [1, 0, 1, 0], [1, 1, 1, 0],
                          [1, 1, 1, 1]]
        s1[0, :, :, 1] = [[0.0, 1, 0, 0], [0, 1, 0, 1], [0, 0, 0, 1],
                          [0, 0, 0, 0]]
        s1[1, :, :, 0] = np.ones((4, 4))
        s2 = np.zeros((3, 4, 4, 2), dtype=np.float32)
        s2[0, :, :, 0] = [[1.0, 0, 1, 1], [1, 0, 1, 0], [1, 1, 1, 0],
                          [1, 1, 1, 1]]
        s2[0, :, :, 1] = [[0.0, 1, 0, 0], [0, 1, 0, 1], [0, 0, 0, 1],
                          [0, 0, 0, 0]]
        s2[1, :, :, 0] = np.ones((4, 4))
        s2[2, :, :, 0] = np.ones((4, 4))
        with tf.Graph().as_default(), tf.Session('') as sess:
            s1_tf = tf.constant(s1, dtype=tf.float32)
            s2_tf = tf.constant(s2, dtype=tf.float32)
            ker = tf.reshape(kernel.Kernel(test_skeleton, s1_tf, s2_tf),
                             [s1.shape[0], s2.shape[0]])
        kernel_tf = sess.run([ker])[0]

        print kernel_tf
        self.assertAlmostEqual(0.80775118, kernel_tf[0, 1])
        self.assertAlmostEqual(0.80775118, kernel_tf[0, 2])
        self.assertAlmostEqual(0.80775118, kernel_tf[1, 0])
        self.assertAlmostEqual(1.0, kernel_tf[0, 0], 6)
        self.assertAlmostEqual(1.0, kernel_tf[1, 1], 6)
        self.assertAlmostEqual(1.0, kernel_tf[1, 2], 6)
示例#4
0
    def TrainRBFKernelServer(self,
                             lmbda=.1,
                             gamma=50.,
                             sampling_factor=1. / 1000.):
        """
        Fit Kernelized RBF Ridge Regression to the current image on the server
        :param lmbda:
        :param gamma: gamma factor to build the kernel (https://en.wikipedia.org/wiki/Radial_basis_function_kernel)
        :param sampling_factor: percentage of pixels to sample to build the model
        :return:
        """
        self._BuildDataSet(sampling_factor, normalize=True)
        inputs = self.inputs
        outputs = self.outputs
        labels_input = self.bands_modeling_estimation_input
        labels_output = self.bands_modeling_estimation_output

        # Train
        self.distance_krr = kernel.RBFDistance(kernel.RBFDistance(gamma))
        self.gamma = gamma
        self.lmbda = lmbda
        self.kernel_rbf = kernel.Kernel(inputs,
                                        labels_input,
                                        self.distance_krr,
                                        weight_property="weight")

        outputs_eeArray = converters.eeFeatureCollectionToeeArray(
            outputs, labels_output)

        self.alpha = self.kernel_rbf.getAlphaeeArray(outputs_eeArray, lmbda)
示例#5
0
def test_put_del_route_unreachable():
    kern = kernel.Kernel(log=None, log_id="", table_name="main")
    if not kern.platform_supported:
        return
    # Add unreachable prefix in the kernel routing table (no next hops)
    prefix = packet_common.make_ip_prefix("99.99.99.99/32")
    nhops = []
    rte = fib_route.FibRoute(prefix, nhops)
    assert kern.put_route(rte)
    tab_str = kern.cli_route_prefix_table(254, prefix).to_string()
    pattern = (r"[|] Table +[|] Main +[|]\n"
               r"[|] Address Family +[|] IPv4 +[|]\n"
               r"[|] Destination +[|] 99\.99\.99\.99/32 +[|]\n"
               r"[|] Type +[|] Unreachable +[|]\n"
               r"[|] Protocol +[|] RIFT +[|]\n"
               r"[|] Scope +[|] Universe +[|]\n"
               r"[|] Next-hops +[|]  +[|]\n"
               r"[|] Priority +[|] 199 +[|]\n")
    assert re.search(pattern, tab_str) is not None
    # Replace unreachable route with a route containing one next hop
    new_nhops = [next_hop.NextHop("lo", packet_common.make_ip_address("127.0.0.1"))]
    rte = fib_route.FibRoute(prefix, new_nhops)
    assert kern.put_route(rte)
    tab_str = kern.cli_route_prefix_table(254, prefix).to_string()
    pattern = (r"[|] Table +[|] Main +[|]\n"
               r"[|] Address Family +[|] IPv4 +[|]\n"
               r"[|] Destination +[|] 99\.99\.99\.99/32 +[|]\n"
               r"[|] Type +[|] Unicast +[|]\n"
               r"[|] Protocol +[|] RIFT +[|]\n"
               r"[|] Scope +[|] Universe +[|]\n"
               r"[|] Next-hops +[|] lo 127.0.0.1 +[|]\n"
               r"[|] Priority +[|] 199 +[|]\n")
    assert re.search(pattern, tab_str) is not None
    # Delete next hops
    assert kern.del_route(prefix)
示例#6
0
def malloc(size):
    address = kernel.Kernel().allocate_memory(size)
    if address is None:
        raise Exception("Couldn't allocate memory")

    LOG.debug("Allocated {} bytes at address {:04X}".format(size, address))
    return address
示例#7
0
    def test_linear_cosistency(self):
        import json
        import copy

        import numpy as np
        import kernel
        import configuration
        import calibration

        # load teset data
        descriptors = np.loadtxt('test_data/c_lin_10.out')
        weights = np.loadtxt('test_data/w_lin_10.out')
        with open('test_data/lin_10.json', 'r') as u_conf:
            user_config = json.load(u_conf)

        # make a list of the allowed qs
        qs = np.arange(1, user_config['nr_modi']+1) * np.pi / user_config['cutoff']

        # read in data and save parameters for calibration comparison
        (_, _, lat, configurations) = calibration.load_data(user_config)
        config = configurations[0]

        # load linear kernel
        kern = kernel.Kernel(*user_config['kernel'])

        # init descriptors of the test configuration
        config.init_nn(user_config['cutoff'], lat)
        config.init_descriptor(qs)

        # make perturbed configs and init them
        dx = 1e-4
        config_plus = copy.deepcopy(config)
        config_minus = copy.deepcopy(config)

        config_plus.positions[0, 0] += dx
        config_minus.positions[0, 0] -= dx

        config_plus.init_nn(user_config['cutoff'], lat)
        config_plus.init_descriptor(qs)

        config_minus.init_nn(user_config['cutoff'], lat)
        config_minus.init_descriptor(qs)

        # build the perturbed matrix elements
        kplus = np.sum(kern.kernel_mat(config_plus.descriptors, descriptors), axis=0)
        kminus = np.sum(kern.kernel_mat(config_minus.descriptors, descriptors), axis=0)

        # make the finite difference values
        eplus = kplus @ weights
        eminus = kminus @ weights

        # calculate forces by finite differences
        Fx_finite = (eplus - eminus) / (2 * dx)

        # calculate forces by regression
        F_reg = kern.force_submat(qs, config, descriptors) @ weights

        print('\n', f'Linear difference: {Fx_finite - F_reg[0]}')
        self.assertAlmostEqual(Fx_finite, F_reg[0], 6)
示例#8
0
def init(error_callback=None):
    global dummy
    global animManager
    global error
    animManager = anim.Manager()
    dummy = kernel.Kernel()
    dummy.Init()
    error = error_callback
示例#9
0
def test_put_del_route_errors():
    kern = kernel.Kernel(log=None, log_id="", table_name="main")
    if not kern.platform_supported:
        return
    # Attempt to add route with nonsense next-hop interface
    prefix = packet_common.make_ip_prefix("99.99.99.99/32")
    nhops = [next_hop.NextHop("nonsense", None)]
    rte = fib_route.FibRoute(prefix, nhops)
    assert not kern.put_route(rte)
示例#10
0
 def test_basics(self):
     """ Tests basic functionality. """
     self.report('Testing basic functionality.')
     kern_1 = kernel.Kernel()
     kern_1.set_hyperparams(param_1=1, param_2=2, param_3=3)
     assert dicts_are_equal(kern_1.hyperparams, self.hyper_param_dict_1)
     kern_1.add_hyperparams(**self.hyper_param_dict_2)
     assert dicts_are_equal(kern_1.hyperparams, self.hyper_param_dict_3)
     kern_1.set_hyperparams(**self.hyper_param_dict_2)
     assert dicts_are_equal(kern_1.hyperparams, self.hyper_param_dict_2)
示例#11
0
文件: main.py 项目: Cloudxtreme/ircd
def main(config):
    logging.getLogger().setLevel(logging.DEBUG)
    server = kernel.Kernel(config)

    def sig_handler(sig, frame):
        server.stop()

    signal.signal(signal.SIGTERM, sig_handler)
    signal.signal(signal.SIGINT, sig_handler)

    server.loop()
示例#12
0
def main():
    """Функция найдет следующий вопрос и отправит в зарегистрированные группы телеграм"""
    app = kernel.Kernel()
    question_quiz = get_question_quiz(
        app=app, question_number=get_question_number(app=app))
    correct_option_id = randomize_options(options=question_quiz.options)

    create_telegram_quiz(
        app=app,
        question=question_quiz.question,
        options=question_quiz.options,
        correct_option_id=correct_option_id,
    )
 def __init__(self,
              stream,
              initial_clusters=1,
              kernelFunction=rbf.rbf,
              initial_points_m=2):
     self.stream = stream
     self.initial_clusters = initial_clusters
     self.kernelFunction = kernelFunction
     self.initial_points_m = initial_points_m
     self.kernel = kernel.Kernel(np.array([[1]], dtype=float),
                                 np.array([1], dtype=float),
                                 np.array([[1]], dtype=float))
     self.clusters = []
     for i in range(0, initial_clusters):
         self.clusters.append(Cluster())
示例#14
0
 def setUp(self):
     cosmo = cosmology.MultiEpoch(0.0, 5.0, cosmo_dict=c_dict)
     lens_dist = kernel.dNdzMagLim(z_min=0.0, z_max=2.0, 
                                   a=2, z0=0.3, b=2)
     source_dist = kernel.dNdzGaussian(z_min=0.0, z_max=2.0,
                                       z0=1.0, sigma_z=0.2)
     lens_window = kernel.WindowFunctionGalaxy(
         lens_dist, cosmo_multi_epoch=cosmo)
     source_window = kernel.WindowFunctionConvergence(
         source_dist, cosmo_multi_epoch=cosmo)
     self.kern = kernel.Kernel(0.001*0.001*degToRad, 1.0*100.0*degToRad,
                            window_function_a=lens_window,
                            window_function_b=source_window,
                            cosmo_multi_epoch=cosmo)
     self.ln_ktheta_array = numpy.linspace(-15, -1, 4)
示例#15
0
def example(num_samples=10,
            num_features=784,
            grid_size=20,
            filename="svm.pdf"):
    samples = np.matrix(
        np.random.normal(size=num_samples * num_features).reshape(
            num_samples, num_features))
    samples = train_x
    labels = 2 * (samples.sum(axis=1) > 0) - 1.0
    labels = train_y - 2
    print("sample variance :", np.var(samples))

    trainer = svmpy.SVMTrainer(kernel.Kernel()._polykernel(120, 1), 0.1)
    predictor = trainer.train(samples, labels)
    predictAll(test_x, test_y, predictor)
示例#16
0
    def __init__(self,
                 theta_min,
                 theta_max,
                 window_function_a,
                 window_function_b,
                 cosmo_dict=None,
                 input_hod=None,
                 halo_dict=None,
                 powSpec=None,
                 **kws):

        self.log_theta_min = numpy.log10(theta_min)
        self.log_theta_max = numpy.log10(theta_max)
        self.theta_array = numpy.logspace(
            self.log_theta_min, self.log_theta_max,
            defaults.default_precision["corr_npoints"])
        if theta_min == theta_max:
            self.log_theta_min = numpy.log10(theta_min)
            self.log_theta_max = numpy.log10(theta_min)
            self.theta_array = numpy.array([theta_min])
        self.wtheta_array = numpy.zeros(self.theta_array.size)

        # Hard coded, but we shouldn't expect halos outside of this range.
        self._k_min = 0.001
        self._k_max = 100.0

        if cosmo_dict == None:
            cosmo_dict = defaults.default_cosmo_dict
        self.cosmo_dict = cosmo_dict

        self.kernel = kernel.Kernel(self._k_min * theta_min,
                                    self._k_max * theta_max, window_function_a,
                                    window_function_b, cosmo_dict)

        self.D_z = self.kernel.cosmo.growth_factor(self.kernel.z_bar)

        if halo_dict is None:
            halo_dict = defaults.default_halo_dict
        self.halo = halo.Halo(self.kernel.z_bar, input_hod, cosmo_dict,
                              halo_dict)
        if powSpec == None:
            powSpec = 'linear_power'
        try:
            self.power_spec = self.halo.__getattribute__(powSpec)
        except AttributeError or TypeError:
            print "WARNING: Invalid input for power spectra varriable,"
            print "\t setting to linear_power"
            self.power_spec = self.halo.__getattribute__('linear_power')
示例#17
0
    def test_linear_energy_subrow(self):
        descr1 = np.eye(20, 10)
        descr2 = np.zeros((20, 10))
        descr2[0, 0] = 1

        kern = kernel.Kernel('linear')
        subrow = np.sum(kern.kernel_mat(descr1, descr2), axis=1)
        self.assertEqual(np.shape(subrow), (20, ))
        self.assertEqual(subrow[0], 1)
        self.assertTrue(np.array_equal(subrow[1:], np.zeros(19)))

        descr2 = np.eye(20, 10)

        subrow = np.sum(kern.kernel_mat(descr1, descr2), axis=1)
        self.assertTrue(np.array_equal(subrow[:10], np.ones(10)))
        self.assertTrue(np.array_equal(subrow[10:], np.zeros(10)))
示例#18
0
def test_cli_addresses_table():
    kern = kernel.Kernel(log=None, log_id="", table_name="main")
    if not kern.platform_supported:
        return
    # We assume the loopback interface (lo) is always there, and we look for something like this:
    # +-----------+------------+------------+----------------+---------+
    # | Interface | Address    | Local      | Broadcast      | Anycast |
    # | Name      |            |            |                |         |
    # +-----------+------------+------------+----------------+---------+
    # | lo        | 127.0.0.1  | 127.0.0.1  |                |         |
    tab_str = kern.cli_addresses_table().to_string()
    pattern = (r"[|] Interface +[|] +Address +[|] +Local +[|] +Broadcast +[|] +Anycast +[|]\n"
               r"[|] Name +[|] +[|] +[|] +[|] +[|]\n"
               r"(.|[\n])*"
               r"[|] lo +[|] 127\.0\.0\.1 +[|] 127\.0\.0\.1 +[|] +[|] +[|]\n")
    assert re.search(pattern, tab_str) is not None
示例#19
0
    def test_linear_energy_matrix_element(self):
        kern = kernel.Kernel('linear')
        descr1 = np.eye(10, 10)
        zero_el = np.sum(kern.kernel_mat(descr1, np.zeros(10)), axis=0)
        self.assertEqual(type(zero_el), np.float64)
        self.assertEqual(zero_el, 0)

        one = np.array([1] + [0 for _ in range(9)])
        one_el = np.sum(kern.kernel_mat(descr1, one), axis=0)
        self.assertEqual(one_el, 1)

        one = np.ones(10)
        ten_el = np.sum(kern.kernel_mat(descr1, one), axis=0)
        self.assertEqual(ten_el, 10)

        five = 5 * one
        fifty_el = np.sum(kern.kernel_mat(descr1, five), axis=0)
        self.assertEqual(fifty_el, 50)
示例#20
0
def test_cli_routes_table():
    packet_common.add_missing_methods_to_thrift()
    kern = kernel.Kernel(log=None, log_id="", table_name="main")
    if not kern.platform_supported:
        return
    # We assume that the main route table always has a default route, and we look for this:
    # +-------------+---------+--------------------+-------------+-----------+-----------+------------+--------+
    # | Table       | Address | Destination        | Type        | Protocol  | Outgoing  | Gateway    | Weight |
    # |             | Family  |                    |             |           | Interface |            |        |
    # +-------------+---------+--------------------+-------------+-----------+-----------+------------+--------+
    # ...
    # | Main        | IPv4    | 0.0.0.0/0          | Unicast     | Boot/Dhcp | eth0      | 172.17.0.1 |        |
    # ...
    tab_str = kern.cli_routes_table(254).to_string()
    pattern = (r"[|] Table +[|] Address +[|] Destination +[|] Type +[|] Protocol +[|] Outgoing +[|] Gateway +[|] Weight +[|]\n"
               r"[|] +[|] Family +[|] +[|] +[|] +[|] Interface +[|] +[|] +[|]\n"
               r"(.|[\n])*"
               r"[|] Main +[|] IPv4 +[|] 0\.0\.0\.0/0 +[|] Unicast +[|]")
    assert re.search(pattern, tab_str) is not None
示例#21
0
def test_cli_links_table():
    kern = kernel.Kernel(log=None, log_id="", table_name="main")
    if not kern.platform_supported:
        return
    # We assume the loopback interface (lo) is always there, and we look for something like this:
    # +-----------+-----------+-------------------+-------------------+-----------+-------+-----------+
    # | Interface | Interface | Hardware          | Hardware          | Link Type | MTU   | Flags     |
    # | Name      | Index     | Address           | Broadcast         |           |       |           |
    # |           |           |                   | Address           |           |       |           |
    # +-----------+-----------+-------------------+-------------------+-----------+-------+-----------+
    # | lo        | 1         | 00:00:00:00:00:00 | 00:00:00:00:00:00 |           | 65536 | UP        |
    # ...
    tab_str = kern.cli_links_table().to_string()
    pattern = (r"[|] Interface +[|] +Interface +[|] +Hardware +[|] +Hardware  +[|] +Link Type +[|] +MTU   +[|] +Flags +[|]\n"
               r"[|] Name      +[|] +Index     +[|] +Address  +[|] +Broadcast +[|] +          +[|] +      +[|] +      +[|]\n"
               r"[|]           +[|] +          +[|] +         +[|] +Address   +[|] +          +[|] +      +[|] +      +[|]\n"
               r"(.|[\n])*"
               r"[|] lo +[|] +[0-9]+ +[|] +[0-9:]+ +[|] +[0-9:]+ +[|] + +[|] +[0-9 ]+[|] +UP +[|]\n")
    assert re.search(pattern, tab_str) is not None
    def _reCalculateKernel(self, point):
        matrix_old = np.copy(self.kernel.kernel_matrix)
        kernel_xt = self.kernelFunction(point, point, 1.5)

        # Calculate gamma
        # = Distances of point_xt to every point in stream
        gamma = np.array([[]], dtype=float)
        for i in range(0, len(self.stream)):
            gamma = np.hstack(
                (gamma, [[self.kernelFunction(point, self.stream[i], 1.5)]]))

        # Calculate gamma transposed
        gamma_transposed = np.transpose(gamma)

        # Generate new matrix K
        old_length = matrix_old.shape[0]
        matrix_size = old_length + 1
        matrix_new = np.zeros((matrix_size, matrix_size))

        # Copy old content
        for i in range(0, old_length):
            for j in range(0, old_length):
                matrix_new[i, j] = matrix_old[i, j]

        matrix_new[0:matrix_size - 1,
                   old_length:matrix_size] = gamma_transposed
        matrix_new[old_length:matrix_size, 0:matrix_size - 1] = gamma
        matrix_new[matrix_size - 1, matrix_size - 1] = kernel_xt

        print(self.stream)
        print(matrix_new)
        print()

        # Calculate the eigenvalues and eigenvectors
        eigenvalues, eigenvectors = np.linalg.eig(matrix_new)
        print(eigenvalues)
        print(eigenvectors)

        # Save only the first C=cluster size eigenvectors and eigenvalues
        return kernel.Kernel(matrix_new, eigenvalues, eigenvectors)
示例#23
0
def predict_linear(u_conf: dict, configurations, C: np.array, q) -> (np.array, np.array, np.array, np.array):
    '''
    Loads the calibration data, initializes the kernel and then builds the linear system with the kernel matrices according to kernel
    '''
    directory = u_conf['file_out']
    C_cal = np.array(np.loadtxt(directory + '/calibration_C.out'), dtype=float)

    kern = kernel.Kernel(*u_conf['kernel'])
    n_conf = u_conf['N_conf']
    n_ion = u_conf['N_ion']
    nc_ni = np.shape(C_cal)[0]
    # will be the super vectors
    E = np.zeros(n_conf)
    # Holds forces flattened
    F = np.zeros(n_conf * n_ion * 3)
    T = np.zeros((n_conf * n_ion * 3, nc_ni))

    # build the linear system

    t_0 = time()
    print('Building K ...', end='\r')
    descr_new = C.reshape(n_conf * n_ion, len(q))
    # das erste Argument ist die aktuelle Konfiguration, das zweite die Referenz-Konfiguration
    # this holds the matrix-elements in the shape [sum_j K(C^beta_j, C^alpha_i)]^beta_(alpha, i)
    K = kern.kernel_mat(descr_new, C_cal)
    K = np.sum(
        K.reshape(n_conf, n_ion, nc_ni),
        axis=1
    )
    print(f'Building K: finished after {time()-t_0:.3} s')

    t_0 = time()
    for alpha in range(n_conf):
        print(f'Building T: {alpha+1}/{n_conf}', end='\r')
        E[alpha] = configurations[alpha].energy
        F[alpha*n_ion*3: (alpha+1)*n_ion*3] = configurations[alpha].forces.flatten()
        T[alpha*n_ion*3:(alpha+1)*n_ion*3] = kern.force_submat(q, configurations[alpha], C_cal)
    print(f'Building T: finished after {time()-t_0:.3} s')

    return (E, F, K, T)
示例#24
0
def test_put_del_route():
    kern = kernel.Kernel(log=None, log_id="", table_name="5")
    if not kern.platform_supported:
        return
    # Put route with one next-hop (with interface but no address)
    prefix = packet_common.make_ip_prefix("99.99.99.99/32")
    nhops = [next_hop.NextHop("lo", None)]
    rte = fib_route.FibRoute(prefix, nhops)
    assert kern.put_route(rte)
    # Delete route just added
    assert kern.del_route(prefix)
    # Put route with one next-hop (with interface and address)
    prefix = packet_common.make_ip_prefix("99.99.99.99/32")
    address = packet_common.make_ip_address("127.0.0.1")
    nhops = [next_hop.NextHop("lo", address)]
    rte = fib_route.FibRoute(prefix, nhops)
    assert kern.put_route(rte)
    # Delete route just added
    assert kern.del_route(prefix)
    # Put ECMP route with multiple next-hop (with interface and address)
    prefix = packet_common.make_ip_prefix("99.99.99.99/32")
    address1 = packet_common.make_ip_address("127.0.0.1")
    address2 = packet_common.make_ip_address("127.0.0.2")
    nhops = [next_hop.NextHop("lo", address1), next_hop.NextHop("lo", address2)]
    rte = fib_route.FibRoute(prefix, nhops)
    assert kern.put_route(rte)
    # Do we display the ECMP route properly?
    tab_str = kern.cli_route_prefix_table(5, prefix).to_string()
    pattern = (r"[|] Table +[|] 5 +[|]\n"
               r"[|] Address Family +[|] IPv4 +[|]\n"
               r"[|] Destination +[|] 99\.99\.99\.99/32 +[|]\n"
               r"[|] Type +[|] Unicast +[|]\n"
               r"[|] Protocol +[|] RIFT +[|]\n"
               r"[|] Scope +[|] Universe +[|]\n"
               r"[|] Next-hops +[|] lo 127\.0\.0\.1 1 +[|]\n"
               r"[|] +[|] lo 127\.0\.0\.2 1 +[|]\n")
    assert re.search(pattern, tab_str) is not None
    # Delete route just added
    assert kern.del_route(prefix)
示例#25
0
def build_linear(u_conf: dict, configurations: list, C: np.array,
                 q: np.array) -> (np.array, np.array, np.array, np.array):
    '''
    Intializes the kernel and then builds the linear system with the kernel matrices according to kernel.
    Already normalizes the data to <E> = 0.
    '''
    kern = kernel.Kernel(*u_conf['kernel'])
    n_conf = u_conf['N_conf']
    n_ion = u_conf['N_ion']
    nc_ni = n_conf * n_ion
    # will be the super vectors
    E = np.zeros(n_conf)
    # Holds forces flattened
    F = np.zeros(n_conf * n_ion * 3)
    # The Matrix that is used for fitting the forces
    T = np.zeros((n_conf * n_ion * 3, nc_ni))

    # reshape descriptors
    descr = C.reshape(n_conf * n_ion, len(q))

    t_0 = time()
    print('Building K:', end='\r')
    # das erste Argument ist die aktuelle Konfiguration, das zweite die Referenz-Konfiguration
    K = kern.kernel_mat(descr, descr)
    K = np.sum(K.reshape(n_conf, n_ion, nc_ni), axis=1)
    print(f'Building K: finished after {time()-t_0:.3} s')

    t_0 = time()
    for alpha in range(n_conf):
        print(f'Building [E, F, T]: {alpha+1}/{n_conf}', end='\r')
        E[alpha] = configurations[alpha].energy
        F[alpha * n_ion * 3:(alpha + 1) * n_ion *
          3] = configurations[alpha].forces.flatten()
        T[alpha * n_ion * 3:(alpha + 1) * n_ion * 3] = kern.force_submat(
            q, configurations[alpha], descr)
    print(f'Building [E, F, T]: finished after {time()-t_0:.3} s')

    return (E, F, K, T)
示例#26
0
 def setUp(self):
     cosmo_multi = cosmology.MultiEpoch(0.0, 5.0, cosmo_dict=c_dict)
     lens_dist = kernel.dNdzMagLim(z_min=0.0, z_max=2.0, 
                                   a=2, z0=0.3, b=2)
     source_dist = kernel.dNdzGaussian(z_min=0.0, z_max=2.0,
                                       z0=1.0, sigma_z=0.2)
     lens_window = kernel.WindowFunctionGalaxy(
         lens_dist, cosmo_multi_epoch=cosmo_multi)
     source_window = kernel.WindowFunctionConvergence(
         source_dist, cosmo_multi_epoch=cosmo_multi)
     kern = kernel.Kernel(0.001*0.001*deg_to_rad, 1.0*100.0*deg_to_rad,
                          window_function_a=lens_window,
                          window_function_b=source_window,
                          cosmo_multi_epoch=cosmo_multi)
     
     zheng = hod.HODZheng(hod_dict)
     cosmo_single = cosmology.SingleEpoch(0.0, cosmo_dict=c_dict)
     h = halo.Halo(input_hod=zheng, cosmo_single_epoch=cosmo_single)
     self.corr = correlation.Correlation(0.001, 1.0,
                                         input_kernel=kern,
                                         input_halo=h,
                                         power_spec='power_mm')
     self.theta_array = numpy.logspace(-3, 0, 4)*deg_to_rad
示例#27
0
import asyncio
import kernel
import filesystem
import threading

async def periodic():
    while True:
        await asyncio.sleep(0.2)

def asyncThread(k, loop):
    """ Asyncio thread calls into kernel, runs event loop forever, breaks on Ctrl-C (for win). """
    try:
        asyncio.set_event_loop(loop)
        k.asyncThreadEntry(loop)
        loop.create_task(periodic())
        loop.run_forever()
    except KeyboardInterrupt:
        k.asyncThreadExit()
        raise

if __name__ == "__main__":
    """ Instantiates kernel in main thread, and passes instance to asyncio thread. """
    k = kernel.Kernel()
    loop = asyncio.get_event_loop()
    threading.Thread(target=asyncThread, args=(k, loop)).start()
    k.workThreadEntry()
示例#28
0
import numpy as np
import kernel
import pandas as pd
import math
import scipy.misc as sc
from PIL import Image

np.set_printoptions(threshold=np.nan)
imagepath = "./images/wedding.png"

kernel = kernel.Kernel(2)
scalar = 32
sensitivity = 190
#image = np.array(pd.read_csv("./watch.txt", delimiter="\t"))
#orig = Image.open("peptide5.jpg")
#orig.show()
image = np.asarray(Image.open(imagepath).convert('L'))
newRange = 1
oldRange = np.amax(image) - np.amin(image)
image = scalar * (newRange / oldRange) * (image - np.amin(image))

entropyArray = np.zeros((len(image) - 1, len(image[0]) - 1))
img_len = len(image) - 1
for i in range(img_len):
    if i % 100 == 0:
        print("computing ", i, " of", img_len)
    for j in range(len(image[0]) - 1):
        subArray = np.array([[image[i][j], image[i][j + 1]],[image[i + 1][j], image[i + 1][j + 1]]])
        ent = kernel.entropic_val(subArray)
        entropyArray[i][j] = ent
示例#29
0
kB = 1.38 * 10**(-33)  # A^2 kg fs^-2 K^-1
eV = 1.602177 * 10**(-19)  # J/eV

a = 10.546640000  # lattice constant in A
mass = m_Si  # We have Silicon
mass_ev = mass * 10**(2 * 15 - 2 * 10) / eV  # eV fs^2 A^-2

with open('user_config.json', 'r') as user_conf:
    u_conf = json.load(user_conf)

directory = u_conf['file_out']
q = np.arange(1, u_conf['nr_modi'] + 1) * np.pi / u_conf['cutoff']
C_cal = np.array(np.loadtxt(directory + '/calibration_C.out'), dtype=float)
w_cal = np.array(np.loadtxt(directory + '/calibration_w.out'), dtype=float)
E_ave, _ = np.array(np.loadtxt(directory + '/calibration_E.out'), dtype=float)
kern = kernel.Kernel(*u_conf['kernel'])


# predicts the forces using the available machine-learned calibration
def predict_forces(config: Configuration):
    config.init_nn(u_conf['cutoff'], u_conf['lattice_vectors'])
    config.init_descriptor(q)
    N_ion, dim = np.shape(config.positions)

    # build the linear system
    # The first argument is the current configuration, the second one is the reference configuration
    K = kern.kernel_mat(config.descriptors, C_cal)
    K = np.sum(K, axis=0)[np.newaxis, :]
    T = kern.force_submat(q, config, C_cal)

    # solve the linear system
示例#30
0
def test_create_kernel():
    _kernel_1 = kernel.Kernel(log=None, log_id="", table_name="main")
    _kernel_2 = kernel.Kernel(log=None, log_id="", table_name=3)