def test_equation(): ''' Use trigonometric identity sin^2 (x) + cos^2 (x) = 1 to generate data, with it: initialize the equation, equation splitting & weights discovery? output format, latex format. Additionally, test evaluator for trigonometric functions ''' global_var.init_caches(set_grids=True) global_var.tensor_cache.memory_usage_properties(obj_test_case=np.ones( (10, 10, 10)), mem_for_cache_frac=25) director = Operator_director() director.operator_assembly() x = np.linspace(0, 2 * np.pi, 100) global_var.grid_cache.memory_usage_properties(obj_test_case=x, mem_for_cache_frac=25) upload_grids(x, global_var.grid_cache) print(global_var.grid_cache.memory) names = ['sin', 'cos'] # simple case: single parameter of a token - power trig_tokens = Token_family('trig') trig_tokens.set_status(unique_specific_token=False, unique_token_type=False, meaningful=True, unique_for_right_part=False) equal_params = {'power': 0, 'freq': 0.2, 'dim': 0} trig_tokens.use_glob_cache() trig_params = OrderedDict([('power', (1., 1.)), ('freq', (0.5, 1.5)), ('dim', (0., 0.))]) trig_tokens.set_params(names, trig_params, equal_params) trig_tokens.set_evaluator(trigonometric_evaluator) eq1 = Equation( tokens=[ trig_tokens, ], basic_structure=[], terms_number=3, max_factors_in_term=2 ) # Задать возможности выбора вероятностей кол-ва множителей # assert False director.constructor.operator.set_sparcity(sparcity_value=1.) eq1.select_target_idx(target_idx_fixed=0) eq1.select_target_idx(operator=director.constructor.operator) print([term.name for term in eq1.structure]) print(eq1.fitness_value) print(eq1.described_variables) print(eq1.evaluate(normalize=False, return_val=True)) print('internal:', eq1.weights_internal, 'final:', eq1.weights_final) raise NotImplementedError
def test_pool(): global_var.init_caches(set_grids=True) global_var.tensor_cache.memory_usage_properties(obj_test_case=np.ones( (10, 10, 10)), mem_for_cache_frac=25) mock_equal_params = {'not_power': 0, 'power': 0} mock_params = {'not_power': (1, 4), 'power': (1, 1)} f1 = Token_family('type_1') f2 = Token_family('type_2') f3 = Token_family('type_3') set_family(f1, names=['t1_1', 't1_2', 't1_3'], params=mock_params, equal_params=mock_equal_params, evaluator=mock_evaluator, meaningful=True) set_family(f2, names=['t2_1', 't2_2', 't2_3', 't2_4'], params=mock_params, equal_params=mock_equal_params, evaluator=mock_evaluator, meaningful=False) set_family(f3, names=['t3_1', 't3_2'], params=mock_params, equal_params=mock_equal_params, evaluator=mock_evaluator, meaningful=True) pool = TF_Pool([f1, f2, f3]) print('meaningful:', [(family.type, family.tokens) for family in pool.families_meaningful]) print('all:', [(family.type, family.tokens) for family in pool.families]) pool.families_cardinality(meaningful_only=True) pool.families_cardinality(meaningful_only=False)
def test_single_token_type(): seed = None if type(seed) != type(None): np.random.seed(seed) folder = sys.path[-1] + 'preprocessing/Wave/' boundary = 15 print(sys.path) u_tensors = download_variable(folder + 'wave_HP.npy', folder + 'Derivatives.npy', boundary, time_axis=0) u_names = Define_Derivatives('u', 3, 2) global_var.init_caches(set_grids=False) global_var.tensor_cache.memory_usage_properties( obj_test_case=u_tensors[0, ...], mem_for_cache_frac=25) upload_simple_tokens(u_names, u_tensors, global_var.tensor_cache) u_tokens = Token_family('U') u_tokens.set_status(unique_specific_token=False, unique_token_type=False, meaningful=True, unique_for_right_part=True) equal_params = {'power': 0} u_token_params = OrderedDict([('power', (1, 2))]) u_tokens.set_params(u_names, u_token_params, equal_params) u_tokens.use_glob_cache() # u_eval_params = {'params_names':['power'], 'params_equality':{'power' : 0}} u_tokens.set_evaluator(simple_function_evaluator) director = Operator_director() director.operator_assembly() tokens = [ u_tokens, ] pop_constructor = operators.systems_population_constructor( tokens=tokens, terms_number=5, max_factors_in_term=1, eq_search_evo=director.constructor.operator) equation_creation_params = {'eq_search_iters': 2} optimizer = moeadd_optimizer(pop_constructor, 7, 20, equation_creation_params, delta=1 / 50., neighbors_number=3) evo_operator = operators.sys_search_evolutionary_operator( operators.mixing_xover, operators.gaussian_mutation) optimizer.set_evolutionary(operator=evo_operator) best_obj = np.concatenate( np.ones([1]), np.zeros(shape=len([ 1 for token_family in tokens if token_family.status['meaningful'] ]))) print(best_obj) raise NotImplementedError
variables[1, :] = u_initial for i_outer in range(0, derivatives.shape[1]): variables[i_outer+2] = derivatives[:, i_outer].reshape(variables[i_outer+1].shape) token_names_der = ['t', ] + list(Define_Derivatives(u_initial.ndim, max_order = 1)) token_names_trig = ['sin', 'cos'] # token_names = {'derivatives' : token_names_der, 'trigonometric' : token_names_trig} # evaluators = {'derivatives' : simple_function_evaluator, 'trigonometric' : trigonometric_evaluator} step = 4*np.pi/999 simple_functions = {} for var_idx in np.arange(variables.shape[0]): simple_functions[token_names_der[var_idx]] = variables[var_idx] derivatives_tokens = Token_family('Derivatives') der_eval_params = {'token_matrices':simple_functions, 'params_names':['power'], 'params_equality':{'power' : 0}} derivatives_tokens.set_evaluator(simple_function_evaluator, **der_eval_params) der_token_params = OrderedDict([('power', (1, 1))]) derivatives_tokens.set_params(token_names_der, der_token_params) derivatives_tokens.set_status(unique_specific_token=True, mandatory = True, unique_for_right_part = False) trigonometric_tokens = Token_family('Trigonometric') trig_eval_params = {'grid':grid, 'params_names':['power', 'freq', 'dim'], 'params_equality':{'power': 0, 'freq':0.05, 'dim':0}} trigonometric_tokens.set_evaluator(trigonometric_evaluator, **trig_eval_params) trig_token_params = OrderedDict([('power', (1, 1)), ('freq', (0.9, 1.1)), ('dim', (0, u_initial.ndim))]) trigonometric_tokens.set_params(token_names_trig, trig_token_params) trigonometric_tokens.set_status(unique_token_type=True) tokens = [trigonometric_tokens, derivatives_tokens] basic_terms = []
def test_TF(): global_var.init_caches(set_grids=True) global_var.tensor_cache.memory_usage_properties(obj_test_case=np.ones( (10, 10, 10)), mem_for_cache_frac=25) family = Token_family('test_type') family.use_glob_cache() family.set_status() mock_equal_params = {'not_power': 0, 'power': 0} mock_params = {'not_power': (1, 4), 'power': (1, 1)} family.set_evaluator(mock_evaluator) names = ['n1', 'n2', 'n3'] family.set_params(names, mock_params, mock_equal_params) print(family.cardinality()) occ, token_example = family.create('n1') print(occ, token_example.name) occ, token_example = family.create() print(occ, token_example.name) occ, token_example = family.create(occupied=['n1', 'n2']) print(occ, token_example.name, token_example.status)
] + Define_Derivatives('u', 1, 1) upload_simple_tokens(u_names, global_var.tensor_cache, u_derivs_stacked) global_var.tensor_cache.use_structural() ''' Далее ряд операций для задания семейств токенов (коорд. ось, исх. функция и её производные в первом семействе, а во втором - тригонометрические функции): задание статуса использования токенов через метод .set_status(...) выбор параметров; названия индивидуальных токенов из семейства; параметры равенства двух множителей одного типа, но с разными параметрами (т.е. когда f(x, p1) == f(x, p2), где p1 и p2 - параметры вроде частоты, степени и т.д.), задание метода оценки значений токена на сетке через .set_evaluator(...) и т.д. ''' u_tokens = Token_family('U') u_tokens.use_glob_cache() u_tokens.set_status(unique_specific_token=False, unique_token_type=False, s_and_d_merged=False, meaningful=True, unique_for_right_part=False) u_token_params = OrderedDict([('power', (1, 1))]) u_equal_params = {'power': 0} u_tokens.set_params(u_names, u_token_params, u_equal_params) u_tokens.set_evaluator(simple_function_evaluator, []) # # k1 = 0.5; k2 = 2 # period_min = k1 * (x[1] - x[0]) # period_max = k2 * (x[-1] - x[0]) # freq_max = 1./period_min; freq_min = 1./period_max;
p_tensors = download_variable(folder + 'p_wolfram.npy', folder + 'p_derivs_w.npy', boundary, time_axis=0) # p_names = Define_Derivatives('p', p_tensors[0].ndim, int((p_tensors.shape[0]-1)/p_tensors[0].ndim)) p_names = Define_Derivatives('p', 3, 3) # p_names = p_names[:-3]; p_tensors = p_tensors[:-3, :, :, :] upload_simple_tokens(p_names, p_tensors, global_var.cache) del p_tensors # p_tensors_named = name_and_tensor_dict(p_names, p_tensors) memory_assesment() time.sleep(5) u_tokens = Token_family('U') u_tokens.use_glob_cache() u_eval_params = { 'params_names': ['power'], 'params_equality': { 'power': 0 } } u_tokens.set_evaluator(simple_function_evaluator, **u_eval_params) u_token_params = OrderedDict([('power', (1, 1))]) u_tokens.set_params(u_names, u_token_params) u_tokens.set_status(unique_specific_token=True, unique_token_type=True, meaningful=True, unique_for_right_part=True)