def future(self, i): #到底需不需要考虑拓扑顺序呢??? if type(self.node_list[i]) != Varnode or self.node_list[i].I == None: return #第一次future是提前做的,因此现在I还可能是空呢 for item in self.node_list[i].next_dashed_list: if self.node_list[item].lval != None: #lval != -inf #e.g. 原来是[j_3, a),现在有[, 99] #把lval换成-inf,变成[-inf, a),然后把这个字符串代入Interval进行初始化 tmp = copy.deepcopy(self.node_list[item]) tmp.lval = str(self.node_list[i].I.lower) s = str(tmp).replace('-inf', '').replace('inf', '') if tmp._type == 'int': e = IntInterval.from_string(s) else: e = FloatInterval.from_string(s) else: #rval != inf #e.g. 原来是(a,j_3),现在有[, 99] #把rval=j_3换成99,变成(a, 99),然后把这个字符串代入Interval进行初始化 tmp = copy.deepcopy(self.node_list[item]) tmp.rval = str(self.node_list[i].I.upper) s = str(tmp).replace('-inf', '').replace('inf', '') #用字符串来初始化不能有inf,而要留空 if tmp._type == 'int': e = IntInterval.from_string(s) else: e = FloatInterval.from_string(s) self.node_list[item].I = e
def load_chosen_path(self): path = [] all_msg_tree_view = self._view.all_msg_scrolled_win.get_child() focus_segment = all_msg_tree_view.get_selection() model, _iter = focus_segment.get_selected() depth = model.iter_depth(_iter) current__id = model.get_value(_iter, 0) current_segment_lower_num = model.get_value(_iter, 1) current_segment_upper_num = model.get_value(_iter, 2) current_segment = FloatInterval.closed(current_segment_lower_num, current_segment_upper_num) path.insert(0, [current__id, current_segment]) parent_iter = _iter for i in range(depth): parent_iter = model.iter_parent(parent_iter) parent_id = model.get_value(parent_iter, 0) parent_segment_lower_num = model.get_value(parent_iter, 1) parent_segment_upper_num = model.get_value(parent_iter, 2) parent_segment = FloatInterval.closed(parent_segment_lower_num, parent_segment_upper_num) path.insert(0, [parent_id, parent_segment]) calibrate_parameter = self.load_chosen_parameter() path.insert(0, [calibrate_parameter, None]) return path
def __init__(self, var_type, interval=None): super(Var, self).__init__() self.var_type = var_type self.interval = {} if var_type == 'int': if interval == None: self.interval['int'] = IntInterval.all() else: self.interval['int'] = IntInterval(interval) elif var_type == 'float': if interval == None: self.interval['float'] = FloatInterval.all() else: self.interval['float'] = FloatInterval(interval)
def calculate_beta_0_interval(self, alpha=0.05, precision=5): x_mean = self.x.mean() delta = x_mean ** 2 / ((self.x - x_mean) ** 2).sum() delta = math.sqrt(delta + self.x.count() ** -1) delta = self.calculate_t_distribute().isf(alpha / 2) * delta * self.calculate_std_e() b0 = self.calculate_Beta0() return FloatInterval.closed(round(b0 - delta, precision), round(b0 + delta, precision))
def calculate_mean_confidence_interval_large(series, confidence_interval=0.90): mean = series.mean() s = math.sqrt(series.var()) count = series.count() z = norm.isf((1 - confidence_interval) / 2) delta = round(z * (s / math.sqrt(count)), 1) return FloatInterval.closed(mean - delta, mean + delta)
def roleta(populacao, start, target): #Calcula um vetor de fitness dos individuos da populacao fitPop = [] porcFitness = [] sumFitness = 0 for individuo in populacao: fitIndividuo = fitness(individuo, start, target) fitPop.append(fitIndividuo) sumFitness += fitIndividuo #Calcula a soma total das fitness #sumFitness = sum(fitPop) #Calcula a porcentagem de cada fitness individual em relacao a fitness total for fit in fitPop: porcFitness.append(round(fit / sumFitness, 2)) # Calcula a posicao da agulha da roleta - numero entre 0 e 1 randomico agulha = np.random.uniform(0, max(porcFitness), 1) / sumFitness #Cria os intervalos da roleta e faz o giro resultado = 0 a = 0 for porc in porcFitness: b = a + porc if float(agulha) in fInterval.closed(a, b): break else: resultado += 1 a = b return populacao[resultado]
def update_calibrate_parameter_interval_combobox(self, widget): self.clear_factors_scrolled_win() self.calibrate_parameter_interval_choose_combobox.clear() last_segment = self._presenter.load_last_dependency_segment() default_segment = FloatInterval.closed(2020, 2020) if last_segment == default_segment: self.clear_calibrate_parameter_interval_combobox() else: try: parameter_segments = self._presenter.get_calibrate_parameter_segments() except ValueError: dialog = Gtk.MessageDialog(parent=self.main_window, flags=0, message_type=Gtk.MessageType.INFO, buttons=Gtk.ButtonsType.OK, text="提示") dialog.format_secondary_text("请先选择好各个依赖分段") dialog.run() dialog.destroy() else: self._parameter_segments = parameter_segments interval_model = Gtk.ListStore(int, str) interval_model.append([2020, '--请先选择校正参数区间--']) count = 0 for segment in parameter_segments: interval = segment[0] lower_num = interval.lower upper_num = interval.upper interval_model.append([count, '[{}, {}]'.format(lower_num, upper_num)]) count += 1 self.calibrate_parameter_interval_choose_combobox.set_model(interval_model) cell = Gtk.CellRendererText() self.calibrate_parameter_interval_choose_combobox.pack_start(cell, True) self.calibrate_parameter_interval_choose_combobox.add_attribute(cell, 'text', 1) self.calibrate_parameter_interval_choose_combobox.set_active(0)
def test_floats_with_step(self): interval = FloatInterval((0, 0.5), step=0.5) assert interval.lower == 0 assert interval.upper == 0.5 assert not interval.lower_inc assert not interval.upper_inc assert interval.step
def calculate_Var_confidence_interval_large(series, confidence_interval=0.95): count = series.count() var = series.var() upper = (count - 1) * var rv = chi2(count - 1) alpha = 1 - confidence_interval return FloatInterval.closed(round(upper / rv.isf(alpha / 2), 2), round(upper / rv.isf(1 - alpha / 2), 2))
def calculate_mean_confidence_interval_small(series, confidence_interval=0.95): mean = series.mean() s = math.sqrt(series.var()) count = series.count() rv = t(count - 1) z = rv.isf((1 - confidence_interval) / 2) delta = round(z * (s / math.sqrt(count)), 2) return FloatInterval.closed(mean - delta, mean + delta)
def calculate_prediction_interval(self, x, alpha=0.05, precision=5): x_mean = self.x.mean() n = self.x.count() delta = (x - x_mean) ** 2 / ((self.x - x_mean) ** 2).sum() delta = math.sqrt(1 + delta + n ** -1) delta = self.calculate_t_distribute().isf(alpha / 2) * delta * self.calculate_std_e() y = x * self.calculate_Beta1() + self.calculate_Beta0() return FloatInterval.closed(round(y - delta, precision), round(y + delta, precision))
def __init__(self, _type, const): super(Constnode, self).__init__(_type) self.const = const val = float(const) if val == int(val) and not const.endswith('.0'): self.I = IntInterval([int(val), int(val)]) #TODO: float else: self.I = FloatInterval([val, val]) #TODO: float
def test_string_as_constructor_param(self): with raises(TypeError) as e: FloatInterval('(0.2, 0.5)') assert str(e.value) == ( 'First argument should be a list or tuple. If you wish to ' 'initialize an interval from string, use from_string factory ' 'method.' )
def link_parameter_nodes_factors(self, repeat_read): all_factors = self._current_calibrate_msg[6] for node in self._parameter_nodes: for segment in node.parameter_segments: left_num = segment[0][0] right_num = segment[0][1] if not repeat_read: interval = FloatInterval.closed(left_num, right_num) else: try: interval = FloatInterval.closed(left_num, right_num) except RangeBoundsException: interval = FloatInterval.closed(left_num, left_num + 2) segment[0] = interval transfer_num = segment[1] factors = all_factors[transfer_num] segment[1] = factors
def show_two_curves_in_senior(self): _id, lower_num, upper_num = self.load_chosen_segment() current_interval = FloatInterval.closed(lower_num, upper_num) current_factors_str = self.load_chosen_factors() current_factors = eval(current_factors_str) modified_factors = self.load_factors_entry() modified_segment = [current_interval, modified_factors] current_segment = [current_interval, current_factors] self._editor.show_two_factors_curve(modified_segment, current_segment)
def load_current_entry(self): interval_list = [] for entry in self._view.entries: num = float(entry.get_text()) interval_list.append(num) lower_num = interval_list[0] upper_num = interval_list[1] interval = FloatInterval.closed(lower_num, upper_num) return interval
def create_dependency_node(segment, dependency_id): dependency_node = entity.CalibrateFile.CalibrateDependencyNode() segment_upper = segment[0][1] segment_lower = segment[0][0] transfer_num = segment[1] dependency_node.parameter_id = dependency_id dependency_node.transfer_num = transfer_num dependency_node.parameter_segment = FloatInterval.closed( segment_lower, segment_upper) return dependency_node
def add_depend_segment_node(self, parent_node, child_id, segment=FloatInterval.closed( float('-inf'), float('inf'))): # 当父节点在分支中的位置不是参数节点的前一级时,需考虑添加多级的分段 child_node = CalibrateDependencyNode() child_node.parameter_segment = segment child_node.parameter_id = child_id child_node.parent = parent_node self._child_node = child_node
def modify_depend_segment(lower_num, upper_num, depend_node): if not isinstance(depend_node, CalibrateDependencyNode): raise TypeError check_lower = isinstance(lower_num, int) or isinstance( lower_num, float) check_upper = isinstance(upper_num, int) or isinstance( upper_num, float) if not check_upper and not check_lower: raise ValueError('upper bound or lower bound type error') new_segment = FloatInterval.closed(lower_num, upper_num) depend_node.parameter_segment = new_segment
def load_last_dependency_segment(self): viewport = self._view.dependencies_segment_choose_scrolled_win.get_child() main_box = viewport.get_child() boxes = main_box.get_children() last_box = boxes[-1] last_combobox = last_box.get_children()[1] segment_activated = last_combobox.get_active() model = last_combobox.get_model() _iter = model.get_iter_from_string('{}'.format(segment_activated)) segment_str = model.get_value(_iter, 0) last_segment = FloatInterval.from_string(segment_str) return last_segment
def add_depend_behind(self, depend_in, new_dependency): for node in self._root_node.descendants: if depend_in == node.parameter_id: children_nodes = node.children node.children = [] depend_node = CalibrateDependencyNode() depend_node.parameter_id = new_dependency default_segment = FloatInterval.closed(float('-inf'), float('inf')) depend_node.parameter_segment = default_segment depend_node.parent = node depend_node.children = children_nodes
def link_dependency_roots(root_node, entry_dependency): for segment in entry_dependency[1]: dependency_segment_node = entity.CalibrateFile.CalibrateDependencyNode( ) parameter_id = entry_dependency[0] dependency_segment_node.parameter_id = parameter_id segment_upper = segment[0][1] segment_lower = segment[0][0] transfer_num = segment[1] interval = FloatInterval.closed(segment_lower, segment_upper) dependency_segment_node.parameter_segment = interval dependency_segment_node.transfer_num = transfer_num dependency_segment_node.parent = root_node
def modify_factors_in_senior(self): path = self.load_chosen_path() path = path[:-1] calibrate_parameter_id, lower_num, upper_num = self.load_chosen_segment( ) current_factors_str = self.load_chosen_factors() current_factors = eval(current_factors_str) current_interval = FloatInterval.closed(lower_num, upper_num) segment = [current_interval, current_factors] modified_factors = self.load_factors_entry() self._editor.modify_parameter_factors_in_senior( self._channel, calibrate_parameter_id, path, segment, modified_factors)
def parse_resistivity(model): """ Given a Boteler resitivity specification *model* (list of depth [m] / resistivity [Ohm/m] tuples), return a conductivity map suitable for func:`conductivity.surface_impedance_1D`. """ conductivity_model = OrderedDict() last_depth = 0 for depth_i, r in model: bound = FloatInterval.closed_open(last_depth, last_depth + depth_i) conductivity_model[bound] = 1 / r last_depth += depth_i return conductivity_model
def load_focus_depend(self): dependencies_segment_choose_scrolled_win = self._view.dependencies_segment_choose_scrolled_win viewport = dependencies_segment_choose_scrolled_win.get_child() main_box = viewport.get_child() focus_box = main_box.get_focus_child() focus_box_children = focus_box.get_children() focus_label = focus_box_children[0] focus_depend_id = int(focus_label.get_text()) focus_combobox = focus_box_children[1] segment_activated = focus_combobox.get_active() model = focus_combobox.get_model() _iter = model.get_iter_from_string('{}'.format(segment_activated)) segment_str = model.get_value(_iter, 0) focus_segment = FloatInterval.from_string(segment_str) return focus_depend_id, focus_segment
def load_chosen_dependency_segment(self, dependency_id): viewport = self._view.dependencies_segment_choose_scrolled_win.get_child() main_box = viewport.get_child() boxes = main_box.get_children() for box in boxes: children = box.get_children() label = children[0] depend = int(label.get_text()) if dependency_id == depend: combobox = children[1] segment_activated = combobox.get_active() model = combobox.get_model() _iter = model.get_iter_from_string('{}'.format(segment_activated)) segment_str = model.get_value(_iter, 0) segment = FloatInterval.from_string(segment_str) return segment
def add_depend_before(self, depend_in, new_dependency): parent_nodes = [] for node in self._root_node.descendants: if depend_in == node.parameter_id: parent_node = node.parent if parent_node not in parent_nodes: parent_nodes.append(parent_node) for node_p in parent_nodes: parent_children = list(node_p.children) node_p.children = [] depend_node = CalibrateDependencyNode() depend_node.parameter_id = new_dependency default_segment = FloatInterval.closed(float('-inf'), float('inf')) depend_node.parameter_segment = default_segment depend_node.parent = node_p depend_node.children = parent_children
def load_parameter_node_path(self): viewport = self._view.dependencies_segment_choose_scrolled_win.get_child() main_box = viewport.get_child() boxes = main_box.get_children() calibrate_parameter = self.load_chosen_calibrate_parameter() parameter_path = [[calibrate_parameter, None]] for box in boxes: children = box.get_children() label = children[0] depend_id = int(label.get_text()) combobox = children[1] segment_activated = combobox.get_active() model = combobox.get_model() _iter = model.get_iter_from_string('{}'.format(segment_activated)) segment_str = model.get_value(_iter, 0) focus_segment = FloatInterval.from_string(segment_str) parameter_path.append([depend_id, focus_segment]) return parameter_path
def update_next_depend_segment(self, widget): self.clear_calibrate_parameter_interval_combobox() self.clear_factors_scrolled_win() viewport = self.dependencies_segment_choose_scrolled_win.get_child() main_box = viewport.get_child() boxes = main_box.get_children() focus_depend_id, focus_segment = self._presenter.load_focus_depend() default_segment = FloatInterval.closed(2020, 2020) focus_depend_id_index = self._depends_id.index(focus_depend_id) if focus_depend_id_index+1 < len(self._depends_id): next_parameter_id = self._depends_id[focus_depend_id_index+1] next_model = Gtk.ListStore(str, str) if focus_segment != default_segment: depend_path = self._presenter.load_depend_path(focus_depend_id) next_segments = self._presenter.get_depend_segments(depend_path, next_parameter_id) next_model.append(['[2020, 2020]', '--请先选择依赖区间--']) for segment in next_segments: lower_num = segment.lower upper_num = segment.upper next_model.append(['[{}, {}]'.format(lower_num, upper_num), '[{}, {}]'.format(lower_num, upper_num)]) next_box = boxes[focus_depend_id_index+1] next_label = next_box.get_children()[0] next_depend_id = int(next_label.get_text()) next_combobox = next_box.get_children()[1] next_combobox.clear() next_combobox.set_model(next_model) current_cell = Gtk.CellRendererText() next_combobox.pack_start(current_cell, True) next_combobox.add_attribute(current_cell, 'text', 1) # next_combobox.set_active(0) # 这里的set_active又会跳回去,陷入无限循环,有毒.. if self._is_update_all_dependencies_segment_choose: if next_depend_id == self._depends_id[-1]: next_combobox.connect('changed', self.update_calibrate_parameter_interval_combobox) self._is_update_all_dependencies_segment_choose = False else: next_combobox.connect('changed', self.update_next_depend_segment) else: for box in boxes[focus_depend_id_index+1:]: combobox = box.get_children()[1] combobox.clear() empty_model = Gtk.ListStore() combobox.set_model(empty_model)
def parse_conductivity(fid): """ Parse a USGS model conductivity file-like object *fid*. Return an ordered mapping between layer depth interval, [upper depth, lower_depth) in [m], and the conductivity [(Ohm-m)^{-1}] """ for line in fid: if line.startswith('*/'): if 'thicknesses' in line.split('!')[1].lower(): thicknesses = map(float, line[1:].split('/')[1].split(',')[:-1]) elif 'resistivities' in line.split('!')[1].lower(): resistivites = map(float, line[1:].split('/')[1].split(',')[:-1]) else: break last_depth = 0 bounds = [] for depth in thicknesses: bounds.append(FloatInterval.closed_open(last_depth, last_depth + depth)) last_depth += depth return OrderedDict(zip(bounds, 1 / NP.array(resistivites)))
def spectrogram_by_eeg_bandwidth(sig, sample_rate=125, timeIntervalSec=30): slow = FloatInterval.from_string('[0.5, 2.0)') delta = FloatInterval.from_string('[2, 4.0)') theta = FloatInterval.from_string('[4.0, 8.0)') alpha = FloatInterval.from_string('[8.0, 16.0)') beta = FloatInterval.from_string('[16.0, 32.0)') gamma = FloatInterval.from_string('[32.0, 100.0)') ##above100Hz = FloatInterval.from_string('[100.0,)') # no signal above100Hz nperseg = int(sample_rate * timeIntervalSec) noverlap = None #will take default value freqs, times, spec = signal.spectrogram(sig, fs=sample_rate, window='hann', nperseg=sample_rate*timeIntervalSec, noverlap=noverlap, detrend=False) #Edelta, Etheta, Ealpha, Ebeta, Egamma, Eabove100Hz = np.zeros(6) result = pd.DataFrame(np.zeros(spec.shape[1]*6).reshape((6, spec.shape[1])), index=['Slow', 'Delta', 'Theta', 'Alpha', 'Beta', 'Gamma']) # for i in range(0, spec.shape[0]): for j in range(0, spec.shape[1]): if freqs[i] in slow: result.loc["Slow", j]= result.loc["Slow", j] + spec[i, j] if freqs[i] in delta: result.loc["Delta", j]= result.loc["Delta", j] + spec[i, j] elif freqs[i] in theta: result.loc["Theta", j]= result.loc["Theta", j] + spec[i, j] elif freqs[i] in alpha: result.loc["Alpha", j]= result.loc["Alpha", j] + spec[i, j] elif freqs[i] in beta: result.loc["Beta", j]= result.loc["Beta", j] + spec[i, j] elif freqs[i] in gamma: result.loc["Gamma", j]= result.loc["Gamma", j] + spec[i, j] # else: we are filtering out frequencies lower than 0.5 Hz # print("error at cell " + str((i, j))) return result
def spectrogram_by_eeg_bandwidth(sig, sample_rate=125, timeIntervalSec=2): delta = FloatInterval.from_string('[0, 4.0)') theta = FloatInterval.from_string('[4.0, 8.0)') alpha = FloatInterval.from_string('[8.0, 16.0)') beta = FloatInterval.from_string('[16.0, 32.0)') gamma = FloatInterval.from_string('[32.0, 100.0)') above100Hz = FloatInterval.from_string('[100.0,)') # nperseg = int(sample_rate * timeIntervalSec) noverlap = 0 freqs, times, spec = signal.spectrogram(sig, fs=sample_rate, window='hann', nperseg=sample_rate*timeIntervalSec, noverlap=noverlap, detrend=False) #Edelta, Etheta, Ealpha, Ebeta, Egamma, Eabove100Hz = np.zeros(6) result = pd.DataFrame(np.zeros(spec.shape[1]*6).reshape((6, spec.shape[1])), index=['Delta', 'Theta', 'Alpha', 'Beta', 'Gamma', 'Above100Hz']) # for i in range(0, spec.shape[0]): for j in range(0, spec.shape[1]): if freqs[i] in delta: result.loc["Delta", j]= result.loc["Delta", j] + spec[i, j] elif freqs[i] in theta: result.loc["Theta", j]= result.loc["Theta", j] + spec[i, j] elif freqs[i] in alpha: result.loc["Alpha", j]= result.loc["Alpha", j] + spec[i, j] elif freqs[i] in beta: result.loc["Beta", j]= result.loc["Beta", j] + spec[i, j] elif freqs[i] in gamma: result.loc["Gamma", j]= result.loc["Gamma", j] + spec[i, j] elif freqs[i] in above100Hz: print(str((i, j)) + "added tp above100Hz") result.loc["Above100Hz", j]= result.loc["Above100Hz", j] + spec[i, j] else: print("error at cell " + str((i, j))) return result
class TestComparisonOperators(object): @mark.parametrize(('comparison', 'result'), ( (IntInterval([1, 3]) == IntInterval([1, 3]), True), (IntInterval([1, 3]) == IntInterval([1, 4]), False), (IntInterval([inf, inf]) == inf, True), (IntInterval([3, 3]) == 3, True), (IntInterval([3, 3]) == 5, False), (IntInterval('(,)') == None, False) )) def test_eq_operator(self, comparison, result): assert comparison is result @mark.parametrize(('comparison', 'result'), ( (IntInterval([1, 3]) != IntInterval([1, 3]), False), (IntInterval([1, 3]) != IntInterval([1, 4]), True), (IntInterval([inf, inf]) != inf, False), (IntInterval([3, 3]) != 3, False), (IntInterval([3, 3]) != 5, True), (IntInterval('(,)') != None, True) )) def test_ne_operator(self, comparison, result): assert comparison is result @mark.parametrize(('comparison', 'result'), ( (IntInterval([1, 3]) > IntInterval([0, 2]), True), (IntInterval((1, 4)) > 1, False), (IntInterval((1, 6)) > [1, 6], False), (IntInterval((1, 6)) > 0, True) )) def test_gt_operator(self, comparison, result): assert comparison is result @mark.parametrize(('comparison', 'result'), ( (IntInterval([1, 3]) >= IntInterval([0, 2]), True), (IntInterval((1, 4)) >= 1, False), (IntInterval((1, 6)) >= [1, 6], False), (IntInterval((1, 6)) >= 0, True) )) def test_ge_operator(self, comparison, result): assert comparison is result @mark.parametrize(('comparison', 'result'), ( (IntInterval([0, 2]) < IntInterval([1, 3]), True), (IntInterval([2, 3]) < IntInterval([2, 3]), False), (IntInterval([2, 5]) < 6, True), (IntInterval([2, 5]) < 5, False), (IntInterval([2, 5]) < inf, True) )) def test_lt_operator(self, comparison, result): assert comparison is result @mark.parametrize(('comparison', 'result'), ( (IntInterval([0, 2]) <= IntInterval([1, 3]), True), (IntInterval([1, 3]) <= IntInterval([1, 3]), True), (IntInterval([1, 7]) <= 8, True), (IntInterval([1, 6]) <= 5, False), (IntInterval([1, 5]) <= inf, True) )) def test_le_operator(self, comparison, result): assert comparison is result def test_integer_comparison(self): assert IntInterval([2, 2]) <= 3 assert IntInterval([1, 3]) >= 0 assert IntInterval([2, 2]) == 2 assert IntInterval([2, 2]) != 3 @mark.parametrize('value', ( IntInterval([0, 2]), 1, (-1, 1), )) def test_contains_operator_for_inclusive_interval(self, value): assert value in IntInterval([-1, 2]) @mark.parametrize('value', ( IntInterval([0, 2]), 2, '[-1, 1]', )) def test_contains_operator_for_non_inclusive_interval(self, value): assert value not in IntInterval((-1, 2)) @mark.parametrize(('interval1', 'interval2', 'expected'), ( (IntInterval((0, 2)), IntInterval((0, 2)), True), (IntInterval([0, 2]), IntInterval([0, 2]), True), (IntInterval('[0, 2)'), IntInterval('[0, 2)'), True), (IntInterval('(0, 2]'), IntInterval('(0, 2]'), True), (IntInterval((0, 2)), IntInterval((1, 2)), False), (IntInterval((0, 2)), IntInterval((0, 1)), False), (IntInterval((0, 2)), IntInterval([0, 1]), False), (IntInterval((0, 2)), FloatInterval((0, 1)), False), )) def test_hash_operator_with_interval_attributes(self, interval1, interval2, expected): actual = (interval1.__hash__() == interval2.__hash__()) assert actual == expected @mark.parametrize(('contains_check', 'expected'), ( (IntInterval([0, 2]) in {IntInterval([0, 2]): ''}, True), (IntInterval([0, 2]) in {IntInterval((0, 2)): ''}, False), (IntInterval([0, 2]) in set([IntInterval([0, 2])]), True), )) def test_hash_operator_with_collections(self, contains_check, expected): assert contains_check is expected
def calculate_beta_1_interval(self, alpha=0.05, precision=5): delta = math.sqrt(((self.x - self.x.mean()) ** 2).sum()) delta = self.calculate_std_e() / delta delta = self.calculate_t_distribute().isf(alpha / 2) * delta b1 = self.calculate_Beta1() return FloatInterval.closed(round(b1 - delta, precision), round(b1 + delta, precision))
class TestIntervalProperties(object): @mark.parametrize(('number_range', 'length'), ( ([1, 4], 3), ([-1, 1], 2), ((-inf, inf), inf), ((1, inf), inf), )) def test_length(self, number_range, length): assert IntInterval(number_range).length == length @mark.parametrize(('number_range', 'radius'), ( ([1, 4], 1.5), ([-1, 1], 1.0), ([-4, -1], 1.5), ((-inf, inf), inf), ((1, inf), inf), )) def test_radius(self, number_range, radius): assert IntInterval(number_range).radius == radius @mark.parametrize(('number_range', 'centre'), ( ([1, 4], 2.5), ([-1, 1], 0), ([-4, -1], -2.5), ((1, inf), inf), )) def test_centre(self, number_range, centre): assert IntInterval(number_range).centre == centre @mark.parametrize(('number_range', 'is_open'), (((2, 3), True), ('(2, 5)', True), ('[3, 4)', False), ('(4, 5]', False), ('3 - 4', False), ([4, 5], False), ('[4, 5]', False))) def test_open(self, number_range, is_open): assert IntInterval(number_range).open == is_open @mark.parametrize( ('number_range', 'is_closed'), (((2, 3), False), ('(2, 5)', False), ('[3, 4)', False), ('(4, 5]', False), ('3 - 4', True), ([4, 5], True), ('[4, 5]', True))) def test_closed(self, number_range, is_closed): assert IntInterval(number_range).closed == is_closed @mark.parametrize(('number_range', 'empty'), ( ((2, 3), True), ([2, 3], False), ([2, 2], False), ((2, 2), True), ('[2, 2)', True), ('(2, 2]', True), ('[2, 3)', False), ((2, 10), False), )) def test_empty(self, number_range, empty): assert IntInterval(number_range).empty == empty @mark.parametrize(('number_range', 'degenerate'), ( ((2, 4), False), ('(2, 2)', True), ('[0, 0)', True), )) def test_degenerate(self, number_range, degenerate): assert IntInterval(number_range).degenerate == degenerate @mark.parametrize( ('interval', 'discrete'), ((IntInterval((2, 3)), True), (IntInterval(5), True), (FloatInterval(3.5), False), (DecimalInterval(Decimal('2.4')), False), (DateTimeInterval(datetime(2002, 1, 1)), False), (DateInterval(date(2002, 1, 1)), True))) def test_discrete(self, interval, discrete): assert interval.discrete == discrete
def calculate_percent_confidence_interval_large(p, n, confidence_interval=0.95): z = norm.isf((1 - confidence_interval) / 2) delta = round(z * math.sqrt(((p * (1 - p)) / n)), 4) return FloatInterval.closed(p - delta, p + delta)
def testCalculateMeanConfidenceIntervalSmall(self): data = pandas.read_excel('mean_smaller.xlsx').age expected = FloatInterval.closed(1476.8, 1503.2) self.assertEqual(expected, sampler.calculate_mean_confidence_interval_small(data))
def testCalculatePercentageConfidenceIntervalLarge(self): expected = FloatInterval.closed(0.5565, 0.7435) self.assertEqual(expected, sampler.calculate_percent_confidence_interval_large(0.65,100))
def testCalculatePercentageConfidenceIntervalLarge(self): data = pandas.read_excel('var_test.xlsx').weight expected = FloatInterval.closed(56.83, 180.39) self.assertEqual(expected, sampler.calculate_Var_confidence_interval_large(data))
def testCalculateMeanConfidenceIntervalLarge(self): data = pandas.read_excel('mean_large.xlsx').age expected = FloatInterval.closed(37.3689326757, 41.6310673243) self.assertEqual(expected, sampler.calculate_mean_confidence_interval_large(data))
def test_interval(self): self.assertEqual(FloatInterval.closed(4.1317,6.13001), self.target.calculate_beta_1_interval()) self.assertEqual(FloatInterval.closed(-4.9130, 554.01347), self.target.calculate_beta_0_interval()) self.assertEqual(FloatInterval.closed(260.13241, 750.745), self.target.calculate_confidence_interval(45)) self.assertEqual(FloatInterval.closed(-293.41195,1304.28935), self.target.calculate_prediction_interval(45))
def test_floats(self): interval = FloatInterval((0.2, 0.5)) assert interval.lower == 0.2 assert interval.upper == 0.5 assert not interval.lower_inc assert not interval.upper_inc