def save_item(self): if len(self.ui.itemNameField.text().strip()) <= 0: self.ui.errorMessagesLabel.setText("Item name is required!") elif item_name_exists(self.ui.itemNameField.text().strip()): self.ui.errorMessagesLabel.setText( "Item with that name already exists in database") elif len(self.ui.itemCostPriceField.text().strip()) <= 0 or ( not is_float(self.ui.itemPriceField.text().strip())): self.ui.errorMessagesLabel.setText( "Cost Price is required! (Use valid characters)") elif len(self.ui.itemPriceField.text().strip()) <= 0 or (not is_float( self.ui.itemPriceField.text().strip())): self.ui.errorMessagesLabel.setText( "Unit Price is required! (Use valid characters)") elif len(self.ui.itemQuantityField.text().strip()) <= 0 or ( not is_integer(self.ui.itemQuantityField.text().strip())): self.ui.errorMessagesLabel.setText( "Quantity is required! (Be sure to enter an integer)") else: item_name = self.ui.itemNameField.text().strip() cost_price = self.ui.itemCostPriceField.text().strip() unit_price = self.ui.itemPriceField.text().strip() quantity = self.ui.itemQuantityField.text().strip() if len(self.ui.itemDescField.toPlainText().strip()) > 0: description = self.ui.itemDescField.toPlainText().strip() if add_item('', item_name, description, cost_price, unit_price, quantity): self.new_item_added.emit() self.close() else: if add_item('', item_name, '', cost_price, unit_price, quantity): self.new_item_added.emit() self.close()
def get_k_value(self) -> int: k_value = 5 if utils.is_integer(self.k_value_edit.text()): k_value = int(self.k_value_edit.text()) if k_value <= 0: k_value = 1 return k_value
def check_edge_out(self, checker): if not self.expr: raise utils.PtpException("Main expression of output inscription is empty", self.source) if self.edge.transition.collective and self.target is not None: raise utils.PtpException("Output edges of collective transitions cannot contain '@'", self.source) allowed = ["bulk", "multicast", "if", "seq"] if self.edge.transition.collective: if self.edge.transition.root: allowed.append("root") allowed += ["scatter", "gather", "allgather", "bcast"] self.check_config(allowed) if self.check_config_with_expression("if"): decls = self.edge.transition.get_input_decls_with_size(self.source) checker.check_expression(self.config["if"], decls, "bool", self.source) if self.check_config_with_expression("seq"): if not utils.is_integer(self.config["seq"]): raise utils.PtpException("Parameter of 'seq' has to be a constant integer", self.source) self.config["seq"] = int(self.config["seq"]) if self.target is not None: checker.check_expression(self.target, self.edge.transition.get_decls(), self.target_type, self.source) self.check(checker)
def mutate(self, x): n = np.size(x) x_new = np.random.normal(x, self.sigma, size=n) if is_integer(x): x_new = np.array(np.round(x_new), dtype=int) x_new_corrected = self.correction.correct(x_new) return x_new_corrected
def check_edge_out(self, checker): if not self.expr: raise utils.PtpException( "Main expression of output inscription is empty", self.source) if self.edge.transition.collective and self.target is not None: raise utils.PtpException( "Output edges of collective transitions cannot contain '@'", self.source) allowed = ["bulk", "multicast", "if", "seq"] if self.edge.transition.collective: if self.edge.transition.root: allowed.append("root") allowed += ["scatter", "gather", "allgather", "bcast"] self.check_config(allowed) if self.check_config_with_expression("if"): decls = self.edge.transition.get_input_decls_with_size(self.source) checker.check_expression(self.config["if"], decls, "bool", self.source) if self.check_config_with_expression("seq"): if not utils.is_integer(self.config["seq"]): raise utils.PtpException( "Parameter of 'seq' has to be a constant integer", self.source) self.config["seq"] = int(self.config["seq"]) if self.target is not None: checker.check_expression(self.target, self.edge.transition.get_decls(), self.target_type, self.source) self.check(checker)
def is_integer_solution(basis, x_opt, int_idx): for i in basis: if i >= len(x_opt): print "Integer fail %s %s %s" % (i, str(x_opt), str(basis)) if i in int_idx and not is_integer(x_opt[i]): return False return True
def is_running(): running = False if os.path.exists(paths.pid_file): with open(paths.pid_file, 'r') as pid_file: pid_content = pid_file.read() running = utils.is_integer(pid_content) return running
def check_totals(self, totals): if len(totals) == 0: err_msg = "Error: No totals have been found on this receipt" return False, err_msg # Assume that no receipt can have more than 2 totals if len(totals) > 2: err_msg = "Error: More than two totals have been found on this receipt" return False, err_msg any_incorrect = False err_msg = None for total in totals: # Each total should have either a sum or an amount (or both) if "sum" in total: if not utils.check_price(total['sum']): any_incorrect = True err_msg = "Error: total with incorrect sum" if "amount" in total: if not utils.is_integer(total['amount']): any_incorrect = True err_msg = "Error: total with incorrect amount" if "sum" not in total and \ "amount" not in total: any_incorrect = True err_msg = "Error: total must have either 'sum' or 'amount'" if any_incorrect: return False, err_msg return True, None
def is_blocked(): blocked = False if os.path.exists(paths.pid_file): with open(paths.pid_file, 'r') as pid_file: pid_content = pid_file.read() blocked = not utils.is_integer(pid_content) return blocked
def __make_user_input_integer(self, status: Status) -> int: message = f'■ {self.status_map[status]}: ' val = input(message) while not is_integer(val) or not self.check_param(status, int(val)): if val == 'q': os._exit(1) print('もう一度入力してください') val = input(message) return int(val)
def mutate(self, x): n = np.size(x) u = np.random.uniform(low=0.0, high=1.0, size=n) r = self.r x_new = x + r * np.tan(np.pi * (u - 1 / 2)) if is_integer(x): x_new = np.array(np.round(x_new), dtype=int) x_new_corrected = self.correction.correct(x_new) return x_new_corrected
def start_vibration(self): left_freq = -1 if utils.is_integer(self.left_freq_edit.text()): left_freq = int(self.left_freq_edit.text()) right_freq = -1 if utils.is_integer(self.right_freq_edit.text()): right_freq = int(self.right_freq_edit.text()) left_power = 204 if utils.is_integer(self.left_power_edit.text()): left_power = int(self.left_power_edit.text()) right_power = 204 if utils.is_integer(self.right_power_edit.text()): right_power = int(self.right_power_edit.text()) if left_freq != -1 and right_freq != -1: utils.start_vibration(self.vibration_serial, left_freq, right_freq, left_power, right_power)
def check_annotation_type(self, text_body): # TODO: What is 'hanging'? if text_body[-1] == ',': return 'hanging' if utils.check_price(text_body): return 'number' if self.parse_date(text_body): return 'date' if utils.is_integer(text_body): return 'int' if self.check_market(text_body): return 'market' if self.check_if_total(text_body): return 'total' return 'text'
def crossover(self, x, y): if is_integer(x): z = np.array([ np.random.randint(np.min([x[i], y[i]]), np.max([x[i], y[i]]) + 1) for i in np.arange(x.size) ], dtype=x.dtype) else: z = np.array([ np.random.uniform(np.min([x[i], y[i]]), np.max([x[i], y[i]])) for i in np.arange(x.size) ], dtype=x.dtype) return z
def check_edge_out(self, checker): self.check_config(("bulk", "multicast", "if", "seq")) if self.check_config_with_expression("if"): decls = self.edge.transition.get_input_decls_with_size(self.source) checker.check_expression(self.config["if"], decls, "bool", self.source) if self.check_config_with_expression("seq"): if not utils.is_integer(self.config["seq"]): raise utils.PtpException("Parameter of 'seq' has to be a constant integer", self.source) self.config["seq"] = int(self.config["seq"]) if self.target is not None: checker.check_expression(self.target, self.edge.transition.get_decls(), self.target_type, self.source) self.check(checker)
def obtain_info_from_line_edits(self): if utils.is_integer(self.start_delay_edit.text()): self.config.start_delay = int(self.start_delay_edit.text()) if utils.is_integer(self.trial_duration_edit.text()): self.config.trial_duration = int(self.trial_duration_edit.text()) if utils.is_integer(self.repetitions_edit.text()): self.config.repetitions = int(self.repetitions_edit.text()) if utils.is_integer(self.relaxation_period_edit.text()): self.config.relaxation_period = int( self.relaxation_period_edit.text()) if utils.is_integer(self.left_freq_edit.text()): self.config.left_frequency = int(self.left_freq_edit.text()) if utils.is_integer(self.right_freq_edit.text()): self.config.right_frequency = int(self.right_freq_edit.text()) self.config.vibration_control = self.vibration_control_checkbox.isChecked( )
# In[5]: rn = np.ones(10) rn # In[6]: rn.dtype # In[7]: from utils import is_integer # new function # In[8]: is_integer(rn) # In[9]: is_integer(zn) # ## De Jong 1 objective function # # Source: http://www.geatbx.com/docu/fcnindex-01.html#P89_3085 # In[10]: from objfun import DeJong1 # In[11]:
def get_katana(self, no_or_name: str) -> KatanaInfo: if is_integer(no_or_name): return self.__get_katana_by_no(no_or_name) return self.__get_katana_by_name(no_or_name)
def branch_bound(c, A_eq, b_eq, basis, int_idx=None, **argv): """ Branch algorithm for integer linear programming Return: node: the optimum node -1: illegal """ ## argv max_iter = argv.get("max_iter", 100) max_iter_sub = argv.get("max_iter", 10000) debug = argv.get("debug", False) deep_first = argv.get("deep", True) num_var = len(c) if int_idx is None: int_idx = range(num_var) tree_dict = {} root_id = 0 root = Node(0, basis_raw=basis) tree_dict[root_id] = root node_stack = [root_id] opt_val = 1e16 opt_nid = 0 active_cut_tot = {} if debug: print "\nInit" print "num_var\t%s" % num_var print "int_idx\t%s" % str(int_idx) for itr in range(max_iter): if len(node_stack) == 0: return opt_nid, tree_dict nid = node_stack.pop() if nid not in tree_dict: return -1 node = tree_dict[nid] if debug: print "\nIteration %s" % itr print "nid\t%s" % nid print "basis pre\t%s" % node.basis_raw ret = node.process(c, A_eq, b_eq, int_idx=int_idx, max_iter=max_iter_sub) if debug: print "Node" print "status\t%s" % node.status print "z\t%s" % node.z_opt print "x\t%s" % node.x_opt print "basis pro\t%s" % node.basis_raw ## Pruning if node.status < 0: sys.stderr.write("SubProblem unsolvable\n") continue if node.z_opt >= opt_val: sys.stderr.write( "SubProblem optimum %s over the best solution %s\n" % (node.z_opt, opt_val)) continue if node.is_int: sys.stderr.write( "SubProblem %s has integer solution %s, optimum %s\n" % (nid, node.x_opt, node.z_opt)) if node.z_opt < opt_val: opt_nid = nid opt_val = node.z_opt continue ## Branch cut_idx = 0 var_idx = None b_val = None for i in node.basis: if not is_integer(node.x_opt[i]) and i in int_idx: var_idx = i b_val = node.x_opt[i] break cut_idx += 1 ### upper bound upper = {} upper.update(node.upper) upper[var_idx] = np.floor(b_val) nid_ub = len(tree_dict) node_ub = Node(nid_ub, pid=nid, basis_raw=node.basis_raw, lower=node.lower, upper=upper) tree_dict[nid_ub] = node_ub ### lower bound lower = {} lower.update(node.lower) lower[var_idx] = np.ceil(b_val) nid_lb = len(tree_dict) node_lb = Node(nid_lb, pid=nid, basis_raw=node.basis_raw, lower=lower, upper=node.upper) tree_dict[nid_lb] = node_lb ### push stack if not deep_first: node_stack.append(nid_ub) node_stack.append(nid_lb) else: node_stack.append(nid_lb) node_stack.append(nid_ub) if debug: print "Branch" print "var\t%s" % var_idx print "val\t%s" % b_val print "stack\t%s" % str(node_stack) return opt_nid, tree_dict
def proc_gomory_cut(c, A, b, basis, **argv): # argv max_iter = argv.get("max_iter", 100) max_iter_sub = argv.get("max_iter_sub", 10000) debug = argv.get("debug", False) int_idx = argv.get("int_idx", None) lu_basis = argv.get("lu_basis") x_basis = argv.get("x_basis") # init row_raw = len(b) col_raw = len(c) if int_idx is None: int_idx = set(range(col_raw)) c_tot = c A_tot = A b_tot = b cut_pool = {} for itr in range(max_iter): row, col = A_tot.shape nonbasis = [i for i in range(col) if i not in basis] if lu_basis is None: B = A_tot.take(basis, axis=1) lu_basis = linalg.lu_factor(B) if x_basis is None: x_basis = linalg.lu_solve(lu_basis, b_tot) cut_idx = None cut_val = None for i in range(row): idx = basis[i] val = x_basis[i] if idx in int_idx and not is_integer(val): cut_idx = i cut_val = val if cut_idx is None: sys.stderr.write("Problem solved\n") return opt, cut_pool ## calc cut if debug: print "\nIteration %s" % itr print "size\t%s %s" % (row, col) print "basis\t%s" % str(basis) print "x_basis\t%s" % x_basis print "cut_idx\t%s" % x_basis y_cut, b_cut = get_gomory_cut(A_tot, x_basis, basis, cut_idx, lu_basis=lu_basis) cid = len(cut_pool) cut_pool[cid] = (y_cut, b_cut) ## add cut c_tot = np.concatenate((c_tot, [0])) A_tot = np.concatenate((A_tot, np.zeros((row, 1))), axis=1) y_tot = np.concatenate((y_cut, [1])) A_tot = np.concatenate((A_tot, [y_tot])) b_tot = np.concatenate((b_tot, [b_cut])) basis.append(col) if debug: print "cut yl\t%s" % str(y_cut) print "cut y0\t%s" % b_cut print "basis\t%s" % str(basis) print "c_tot\t%s" % str(c_tot) print "b_tot\t%s" % str(b_tot) opt = simplex_dual(c_tot, A_tot, b_tot, basis, ret_lu=True, max_iter=max_iter_sub) if type(opt) == int: sys.stderr.write("Problem unsolvable\n") return -1 basis = opt.basis x_basis = opt.x_basis lu_basis = opt.lu_basis if debug: print opt return opt, cut_pool
def correct(self, x): d = self.of.b - self.of.a x = self.of.a + np.mod(x - self.of.a, d + (1 if is_integer(x) else 0)) return x
elif VALUE_text.lower() in ['nasopharyngeal aspirate & throat swab', 'nasopharyngeal aspirate and throat swab']: info_for_yaml_dict['sample']['specimen_source'] = [field_to_term_to_uri_dict['ncbi_speciesman_source']['nasopharyngeal aspirate'], field_to_term_to_uri_dict['ncbi_speciesman_source']['throat swab']] elif VALUE_text.lower() in ['nasal swab and throat swab']: info_for_yaml_dict['sample']['specimen_source'] = [field_to_term_to_uri_dict['ncbi_speciesman_source']['nasal swab'], field_to_term_to_uri_dict['ncbi_speciesman_source']['throat swab']] elif VALUE_text.lower() in ['nasal-swab and oro-pharyngeal swab']: info_for_yaml_dict['sample']['specimen_source'] = [field_to_term_to_uri_dict['ncbi_speciesman_source']['nasal swab'], field_to_term_to_uri_dict['ncbi_speciesman_source']['oropharyngeal swab']] elif VALUE_text.strip("'") not in ['missing', 'not collected', 'unknown', 'not provided', 'not applicable', 'N/A']: missing_value_list.append('\t'.join([accession, 'specimen_source', VALUE_text])) elif TAG_text in ['host_sex', 'host sex']: if VALUE_text.lower() not in ['missing', 'not provided']: if VALUE_text in ['male', 'female']: info_for_yaml_dict['host']['host_sex'] = "http://purl.obolibrary.org/obo/PATO_0000384" if VALUE_text == 'male' else "http://purl.obolibrary.org/obo/PATO_0000383" else: missing_value_list.append('\t'.join([accession, 'host_sex', VALUE_text])) elif TAG_text in ['host_age', 'host age']: if is_integer(VALUE_text): host_age = int(VALUE_text) if host_age >= 0 and host_age < 110: info_for_yaml_dict['host']['host_age'] = host_age info_for_yaml_dict['host']['host_age_unit'] = 'http://purl.obolibrary.org/obo/UO_0000036' elif TAG_text == 'collected_by': if VALUE_text.lower() not in ['not available', 'missing']: name = VALUE_text in ['Dr. Susie Bartlett', 'Ahmed Babiker', 'Aisi Fu', 'Brandi Williamson', 'George Taiaroa', 'Natacha Ogando', 'Tim Dalebout', 'ykut Ozdarendeli'] info_for_yaml_dict['sample']['collector_name' if name else 'collecting_institution'] = VALUE_text elif TAG_text == 'collecting institution': if VALUE_text.lower() not in ['not provided', 'na']: info_for_yaml_dict['sample']['collecting_institution'] = VALUE_text elif TAG_text in ['collection_date', 'collection date']: if VALUE_text.lower() not in ['not applicable', 'missing', 'na']: date_to_write = VALUE_text
info_for_yaml_dict['host'][ 'host_health_status'] = field_to_term_to_uri_dict[ 'ncbi_host_health_status'][ GBQualifier_value_text_list[1]] else: missing_value_list.append('\t'.join([ accession_version, 'host_sex or host_health_status', GBQualifier_value_text_list[1] ])) # Host age host_age = -1 if len(GBQualifier_value_text_list[1].split( ' ')) > 1 and is_integer( GBQualifier_value_text_list[1]. split(' ')[-1]): host_age = int( GBQualifier_value_text_list[1].split( ' ')[-1]) elif len(GBQualifier_value_text_list ) > 2 and is_integer( GBQualifier_value_text_list[2]. split(' ')[-1]): host_age = int( GBQualifier_value_text_list[2].split( ' ')[-1]) if host_age > -1: info_for_yaml_dict['host'][ 'host_age'] = host_age
def test_is_integer(): assert is_integer('931229') assert not is_integer('asd123') assert is_integer('0123')
def extract_features_clicked(self): # Construct filter settings to loaded data. bandpass_min = -1 bandpass_max = -1 notch_filter = self.notch_filter_checkbox.isChecked() if utils.is_float(self.bandpass_min_edit.text()): bandpass_min = float(self.bandpass_min_edit.text()) if utils.is_float(self.bandpass_max_edit.text()): bandpass_max = float(self.bandpass_max_edit.text()) adaptive_settings = None if self.adaptive_filtering_checkbox.isChecked(): reference_electrode = int(self.adaptive_reference_electrode.text()) frequencies = [] widths = [] for freq_str in self.adaptive_frequencies_edit.text().split(","): frequencies.append(float(freq_str)) for width_str in self.adaptive_bandwidths_edit.text().split(","): widths.append(float(width_str)) adaptive_settings = utils.AdaptiveFilterSettings(reference_electrode, frequencies, widths) reference_electrode = 0 if self.re_reference_checkbox.isChecked() and utils.is_integer(self.reference_electrode_edit.text()): reference_electrode = int(self.reference_electrode_edit.text()) filter_settings = utils.FilterSettings(global_config.SAMPLING_RATE, bandpass_min, bandpass_max, notch_filter=notch_filter, adaptive_filter_settings=adaptive_settings, reference_electrode=reference_electrode) if self.root_directory_changed: self.loaded_eeg_data = utils.load_data(self.root_directories) eeg_data, classes, sampling_rate, self.trial_classes = \ utils.slice_and_filter_data(self.root_directories, filter_settings, self.loaded_eeg_data) labels = np.array(classes).reshape((-1, 1)) if len(eeg_data) != 0 and len(classes) != 0: print("Data loaded successfully") else: print("Could not load data") return # Construct feature descriptors. # Obtain the range of channels to be included electrode_list = [] for electrode_str in self.electrodes_edit.text().split(","): electrode_list.append(int(electrode_str)) fft_window_size = float(self.fft_window_combo.currentText()) feature_types = [] if self.band_amplitude_checkbox.isChecked(): band_amplitude_min_freq = -1 band_amplitude_max_freq = -1 if utils.is_float(self.band_amplitude_min_edit.text()): band_amplitude_min_freq = float(self.band_amplitude_min_edit.text()) if utils.is_float(self.band_amplitude_max_edit.text()): band_amplitude_max_freq = float(self.band_amplitude_max_edit.text()) if band_amplitude_min_freq != -1 and band_amplitude_max_freq != -1: feature_types.append( utils.AverageBandAmplitudeFeature( utils.FrequencyBand(band_amplitude_min_freq, band_amplitude_max_freq), fft_window_size)) if self.frequency_bands_checkbox.isChecked(): band_width = -1 peak_frequency = self.peak_frequency_checkbox.isChecked() if utils.is_float(self.band_width_edit.text()): band_width = float(self.band_width_edit.text()) center_frequencies_str_list = self.center_frequencies_edit.text().split(",") center_frequencies = [] for center_freq_str in center_frequencies_str_list: if utils.is_float(center_freq_str): center_frequencies.append(float(center_freq_str)) if len(center_frequencies) != 0 and band_width != -1: feature_types.append( utils.FrequencyBandsAmplitudeFeature(center_frequencies, band_width, fft_window_size, peak_frequency)) feature_extraction_info = utils.FeatureExtractionInfo(sampling_rate, electrode_list) self.filter_settings = filter_settings self.feature_extraction_info = feature_extraction_info self.feature_types = feature_types # Extract features extracted_data = utils.extract_features( eeg_data, feature_extraction_info, feature_types) feature_matrix = data.construct_feature_matrix(extracted_data) self.data_set = DataSet(feature_matrix, labels, add_x0=False, shuffle=False) print("Features extracted successfully...")