How to use predecessor method in avocado

Best Python code snippet using avocado_python

fareysequences.py

Source:fareysequences.py Github

copy

Full Screen

...62 if successor == Fraction(1, 1):63 return __predecessor_of_one_first_in_Fm(m)64 ref_point = ceil((successor.numerator * m) /65 successor.denominator)66 return __get_numerator_and_return_predecessor(67 __find_numerator_of_predecessor((ref_point - successor.numerator, ref_point - 1),68 successor), successor)697071def successor_in_Fm(m: int, predecessor: Fraction) -> Fraction:72 # See Lemma 2.9(ii) and Table 2.3 of the monograph. Call for instance:73 # >>> successor_in_Fm(6, Fraction(1, 3))74 # to get the result:75 # Fraction(2, 5)76 if m < 1:77 # "N/A: Order m of the sequence should be > 0"78 return Fraction(1, -1)79 if (predecessor < Fraction(0, 1)) or (predecessor >= Fraction(1, 1)):80 # "N/A: predecessor should be between (0/1) (included) and (1/1) (excluded)"81 return Fraction(1, -2)82 if predecessor.denominator > m:83 # "N/A: Denominator of the predecessor should not exceed the order m of the sequence"84 return Fraction(1, -3)85 if predecessor == Fraction(0, 1):86 return __successor_of_zero_first_in_Fm(m)87 ref_point = ceil((predecessor.numerator * m + 2) /88 predecessor.denominator)89 return __get_numerator_and_return_successor(90 __find_numerator_of_successor(91 (ref_point - predecessor.numerator, ref_point - 1), predecessor),92 predecessor)939495def predecessor_in_Fml(m: int, l: int, successor: Fraction) -> Fraction:96 # See Lemma 2.13(i)(a)-(b) and Table 2.1 of the monograph. Call for instance:97 # >>> predecessor_in_Fml(6, 4, Fraction(1, 1))98 # to get the result:99 # Fraction(4, 5)100 if m < 2:101 # "N/A: Parameter m of the sequence should be > 1"102 return Fraction(1, -1)103 if (l <= 0) or (l >= m):104 # "N/A: Parameter l should be between 0 (excluded) and m (excluded)"105 return Fraction(1, -2)106 if (successor <= Fraction(0, 1)) or (successor > Fraction(1, 1)):107 # "N/A: successor should be between (0/1) (excluded) and (1/1) (included)"108 return Fraction(1, -3)109 if successor.denominator > m:110 # "N/A: Denominator of the successor should not exceed the parameter m of the sequence"111 return Fraction(1, -4)112 if l < successor.numerator:113 # "N/A: Numerator of the successor should be between 1 (included) and l (included)"114 return Fraction(1, -5)115 if successor == Fraction(1, 1):116 return __predecessor_of_one_first_in_Fml(l)117 if successor.numerator * m - successor.denominator * l >= 1:118 return __get_numerator_and_return_predecessor(119 __find_numerator_of_predecessor((l - successor.numerator + 1, l), successor), successor)120 else:121 ref_point = ceil((successor.numerator * m) / successor.denominator)122 return __get_numerator_and_return_predecessor(123 __find_numerator_of_predecessor((ref_point - successor.numerator, ref_point - 1),124 successor), successor)125126127def successor_in_Fml(m: int, l: int, predecessor: Fraction) -> Fraction:128 # See Lemma 2.13(ii)(a)-(b) and Table 2.3 of the monograph. Call for instance:129 # >>> successor_in_Fml(6, 4, Fraction(4, 5))130 # to get the result:131 # Fraction(1, 1)132 if m < 2:133 # "N/A: Parameter m of the sequence should be > 1"134 return Fraction(1, -1)135 if (l <= 0) or (l >= m):136 # "N/A: Parameter l should be between 0 (excluded) and m (excluded)"137 return Fraction(1, -2)138 if (predecessor < Fraction(0, 1)) or (predecessor >= Fraction(1, 1)):139 # "N/A: predecessor should be between (0/1) (included) and (1/1) (excluded)"140 return Fraction(1, -3)141 if predecessor.denominator > m:142 # "N/A: Denominator of the predecessor should not exceed the parameter m of the sequence"143 return Fraction(1, -4)144 if l < predecessor.numerator:145 # "N/A: "N/A: Numerator of the predecessor should be between 1 (included) and l (included)"146 return Fraction(1, -5)147 if predecessor == Fraction(0, 1):148 return __successor_of_zero_first_in_Fml(m)149 if predecessor.denominator * l - predecessor.numerator * m >= 1:150 ref_point = ceil((predecessor.numerator * m + 2) /151 predecessor.denominator)152 return __get_numerator_and_return_successor(153 __find_numerator_of_successor(154 (ref_point - predecessor.numerator, ref_point - 1), predecessor),155 predecessor)156 else:157 return __get_numerator_and_return_successor(158 __find_numerator_of_successor((l - predecessor.numerator + 1, l),159 predecessor), predecessor)160161162def predecessor_in_Gml(m: int, l: int, successor: Fraction) -> Fraction:163 # See Lemma 2.15(i)(a)-(b) and Table 2.1 of the monograph. Call for instance:164 # >>> predecessor_in_Gml(6, 4, Fraction(1, 3))165 # to get the result:166 # Fraction(0, 1)167 if m < 2:168 # "N/A: Parameter m of the sequence should be > 1"169 return Fraction(1, -1)170 if (l <= 0) or (l >= m):171 # "N/A: Parameter l should be between 0 (excluded) and m (excluded)"172 return Fraction(1, -2)173 if (successor <= Fraction(0, 1)) or (successor > Fraction(1, 1)):174 # "N/A: successor should be between (0/1) (excluded) and (1/1) (included)"175 return Fraction(1, -3)176 if successor.denominator > m:177 # "N/A: Denominator of the successor should not exceed the parameter m of the sequence"178 return Fraction(1, -4)179 if l + successor.denominator - m > successor.numerator:180 # "N/A: The quantity (l + denominator - m) should not exceed the numerator of the successor"181 return Fraction(1, -5)182 if successor == Fraction(1, 1):183 return __predecessor_of_one_first_in_Gml(l)184 if successor.numerator * m - successor.denominator * l >= 1:185 ref_point = ceil((successor.numerator * m) /186 successor.denominator)187 return __get_numerator_and_return_predecessor(188 __find_numerator_of_predecessor(189 (ref_point - successor.numerator, ref_point - 1), successor),190 successor)191 else:192 ref_point = ceil(193 (successor.numerator * (m - l)) / (successor.denominator - successor.numerator))194 return __get_numerator_and_return_predecessor(195 __find_numerator_of_predecessor(196 (ref_point - successor.numerator, ref_point - 1), successor),197 successor)198199200def successor_in_Gml(m: int, l: int, predecessor: Fraction) -> Fraction:201 # See Lemma 2.15(ii)(a)-(b) and Table 2.3 of the monograph. Call for instance:202 # >>> successor_in_Gml(6, 4, Fraction(1, 3))203 # to get the result:204 # Fraction(1, 2)205 if m < 2:206 # "N/A: Parameter m of the sequence should be > 1"207 return Fraction(1, -1)208 if (l <= 0) or (l >= m):209 # "N/A: Parameter l should be between 0 (excluded) and m (excluded)"210 return Fraction(1, -2)211 if (predecessor < Fraction(0, 1)) or (predecessor >= Fraction(1, 1)):212 # "N/A: predecessor should be between (0/1) (included) and (1/1) (excluded)"213 return Fraction(1, -3)214 if predecessor.denominator > m:215 # "N/A: Denominator of the predecessor should not exceed the parameter m of the sequence"216 return Fraction(1, -4)217 if l + predecessor.denominator - m > predecessor.numerator:218 # "N/A: Denominator of the predecessor minus its numerator should not exceed (m - l)"219 return Fraction(1, -5)220 if predecessor == Fraction(0, 1):221 return __successor_of_zero_first_in_Gml(m, l)222 if predecessor.denominator * l - predecessor.numerator * m >= 1:223 ref_point = ceil((predecessor.numerator * (m - l) + 2) /224 (predecessor.denominator - predecessor.numerator))225 return __get_numerator_and_return_successor(226 __find_numerator_of_successor(227 (ref_point - predecessor.numerator, ref_point - 1), predecessor),228 predecessor)229 else:230 ref_point = ceil((predecessor.numerator * m + 2) /231 predecessor.denominator)232 return __get_numerator_and_return_successor(233 __find_numerator_of_successor(234 (ref_point - predecessor.numerator, ref_point - 1), predecessor),235 predecessor)236237238def __predecessor_in_FB2mm(m: int, successor: Fraction) -> Fraction:239 # See Remark 1.17 and Table 1.5;240 # see Remark 2.25 and Table 2.8;241 # see Remark 2.11 and Table 2.5;242 # see Remark 2.24 and Table 2.7;243 # see Proposition 2.12 (i) (a) and Proposition 2.12 (ii) (a), and Table 2.1 of the monograph. Call for instance:244 # >>> __predecessor_in_FB2mm(3, Fraction(2, 5))245 # to get the result:246 # Fraction(1, 3)247 if m < 1:248 # "N/A: Parameter m of the sequence should be > 0"249 return Fraction(1, -1)250 if (successor <= Fraction(0, 1)) or (successor > Fraction(1, 1)):251 # "N/A: successor should be between (0/1) (excluded) and (1/1) (included)"252 return Fraction(1, -2)253 if successor.denominator > 2 * m:254 # "N/A: Denominator of the successor should not exceed (2 * m)"255 return Fraction(1, -3)256 if (successor.denominator - m > successor.numerator) or (successor.numerator > m):257 # "N/A: Numerator of the successor should be between (denominator - m) (included) and m (included)"258 return Fraction(1, -4)259 match successor:260 case Fraction(numerator=1, denominator=1):261 return __predecessor_of_one_first_in_FB2mm(m)262 case Fraction(numerator=2, denominator=3):263 return __predecessor_of_two_thirds_in_FB2mm(m)264 case Fraction(numerator=1, denominator=2):265 return __predecessor_of_one_second_in_FB2mm(m)266 case Fraction(numerator=1, denominator=3):267 return __predecessor_of_one_third_in_FB2mm(m)268 case _:269 if successor > Fraction(1, 2):270 return __get_numerator_and_return_predecessor(271 __find_numerator_of_predecessor((m - successor.numerator + 1, m),272 successor), successor)273 else:274 ref_point = ceil((successor.numerator * m) /275 (successor.denominator - successor.numerator))276 return __get_numerator_and_return_predecessor(277 __find_numerator_of_predecessor(278 (ref_point - successor.numerator, ref_point - 1), successor),279 successor)280281282def __successor_in_FB2mm(m: int, predecessor: Fraction) -> Fraction:283 # See Remark 1.17 and Table 1.5;284 # see Remark 2.24 and Table 2.7;285 # see Remark 2.11 and Table 2.5;286 # see Remark 2.25 and Table 2.8;287 # see Proposition 2.12 (i) (b) and Proposition 2.12 (ii) (b), and Table 2.3 of the monograph. Call for instance:288 # >>> __successor_in_FB2mm(3, Fraction(3, 5))289 # to get the result:290 # Fraction(2, 3)291 if m < 1:292 # "N/A: Parameter m of the sequence should be > 0"293 return Fraction(1, -1)294 if (predecessor < Fraction(0, 1)) or (predecessor >= Fraction(1, 1)):295 # "N/A: predecessor should be between (0/1) (included) and (1/1) (excluded)"296 return Fraction(1, -2)297 if predecessor.denominator > 2 * m:298 # "N/A: Denominator of the predecessor should not exceed (2 * m)"299 return Fraction(1, -3)300 if (predecessor.denominator - m > predecessor.numerator) or (predecessor.numerator > m):301 # "N/A: Numerator of the predecessor should be between (denominator - m) (included) and m (included)"302 return Fraction(1, -4)303 match predecessor:304 case Fraction(numerator=0, denominator=1):305 return __successor_of_zero_first_in_FB2mm(m)306 case Fraction(numerator=1, denominator=3):307 return __successor_of_one_third_in_FB2mm(m)308 case Fraction(numerator=1, denominator=2):309 return __successor_of_one_second_in_FB2mm(m)310 case Fraction(numerator=2, denominator=3):311 return __successor_of_two_thirds_in_FB2mm(m)312 case _:313 if predecessor < Fraction(1, 2):314 ref_point = ceil((predecessor.numerator * m + 2) /315 (predecessor.denominator - predecessor.numerator))316 return __get_numerator_and_return_successor(317 __find_numerator_of_successor(318 (ref_point - predecessor.numerator, ref_point - 1), predecessor),319 predecessor)320 else:321 return __get_numerator_and_return_successor(322 __find_numerator_of_successor((m - predecessor.numerator + 1, m),323 predecessor), predecessor)324325326def predecessor_in_FBnm(n: int, m: int, successor: Fraction) -> Fraction:327 # See Remark 1.17 and Table 1.5 of the monograph;328 # see CORRECTED Remark 2.43(i) and Remark 2.43(ii) and CORRECTED Table 2.8;329 # see Remark 2.17 and Table 2.5;330 # See CORRECTED Remark 2.42 and Table 2.7;331 # see Propositions 2.18(i)(a) and 2.18(ii)(a), and Table 2.1;332 # see Propositions 2.19(i)(a) and 2.19(ii)(a), and Table 2.1. Call for instance:333 # >>> predecessor_in_FBnm(6, 4, Fraction(3, 4))334 # to get the result:335 # Fraction(2, 3)336 if n == 2 * m:337 return __predecessor_in_FB2mm(m, successor)338 if n < 2:339 # "N/A: Parameter n of the sequence should be > 1"340 return Fraction(1, -1)341 if (m < 1) or (m >= n):342 # "N/A: Parameter m of the sequence should be between 0 (excluded) and n (excluded)"343 return Fraction(1, -2)344 if (successor <= Fraction(0, 1)) or (successor > Fraction(1, 1)):345 # "N/A: successor should be between (0/1) (excluded) and (1/1) (included)"346 return Fraction(1, -3)347 if successor.denominator > n:348 # "N/A: Denominator of the successor should not exceed the parameter n of the sequence"349 return Fraction(1, -4)350 if (m + successor.denominator - n > successor.numerator) or (successor.numerator > m):351 # "N/A: Numerator of the successor should be between (m + denominator - n) (included) and m (included)"352 return Fraction(1, -5)353 match successor:354 case Fraction(numerator=1, denominator=1):355 return __predecessor_of_one_first_in_FBnm(m)356 case Fraction(numerator=2, denominator=3):357 return __predecessor_of_two_thirds_in_FBnm(n, m)358 case Fraction(numerator=1, denominator=2):359 return __predecessor_of_one_second_in_FBnm(n, m)360 case Fraction(numerator=1, denominator=3):361 return __predecessor_of_one_third_in_FBnm(n, m)362 case _:363 if n < 2 * m:364 if (successor > Fraction(1, 2)) and (successor.numerator * n - successor.denominator * m >= 1):365 return __get_numerator_and_return_predecessor(366 __find_numerator_of_predecessor((m - successor.numerator + 1, m), successor), successor)367 else:368 ref_point = ceil(369 successor.numerator * (n - m) / (successor.denominator - successor.numerator))370 return __get_numerator_and_return_predecessor(371 __find_numerator_of_predecessor((ref_point - successor.numerator, ref_point - 1),372 successor), successor)373 else:374 if (successor > Fraction(1, 2)) or (successor.numerator * n - successor.denominator * m >= 1):375 return __get_numerator_and_return_predecessor(376 __find_numerator_of_predecessor((m - successor.numerator + 1, m), successor), successor)377 else:378 ref_point = ceil(379 successor.numerator * (n - m) / (successor.denominator - successor.numerator))380 return __get_numerator_and_return_predecessor(381 __find_numerator_of_predecessor((ref_point - successor.numerator, ref_point - 1),382 successor), successor)383384385def successor_in_FBnm(n: int, m: int, predecessor: Fraction) -> Fraction:386 # See Remark 1.17 and Table 1.5 of the monograph;387 # see CORRECTED Remark 2.42 and Table 2.7;388 # see Remark 2.17 and Table 2.5;389 # see Remark 2.43(i)-(ii) and Table 2.8;390 # see Propositions 2.18(i)(b) and 2.18(ii)(b), and Table 2.3;391 # see Propositions 2.19(i)(b) and 2.19(ii)(b), and Table 2.3. Call for instance:392 # >>> successor_in_FBnm(6, 4, Fraction(4, 5))393 # to get the result:394 # Fraction(1, 1)395 if n == 2 * m:396 return __successor_in_FB2mm(m, predecessor)397 if n < 2:398 # "N/A: Parameter n of the sequence should be > 1"399 return Fraction(1, -1)400 if (m < 1) or (m >= n):401 # "N/A: Parameter m of the sequence should be between 0 (excluded) and n (excluded)"402 return Fraction(1, -2)403 if (predecessor < Fraction(0, 1)) or (predecessor >= Fraction(1, 1)):404 # "N/A: predecessor should be between (0 % 1) (included) and (1 % 1) (excluded)"405 return Fraction(1, -3)406 if predecessor.denominator > n:407 # "N/A: Denominator of the predecessor should not exceed the parameter n of the sequence"408 return Fraction(1, -4)409 if (m + predecessor.denominator - n > predecessor.numerator) or (predecessor.numerator > m):410 # "N/A: Numerator of the predecessor should be between (m + denominator - n) (included) and m (included)"411 return Fraction(1, -5)412 match predecessor:413 case Fraction(numerator=0, denominator=1):414 return __successor_of_zero_first_in_FBnm(n, m)415 case Fraction(numerator=1, denominator=3):416 return __successor_of_one_third_in_FBnm(n, m)417 case Fraction(numerator=1, denominator=2):418 return __successor_of_one_second_in_FBnm(n, m)419 case Fraction(numerator=2, denominator=3):420 return __successor_of_two_thirds_in_FBnm(n, m)421 case _:422 if n < 2 * m:423 if (predecessor > Fraction(1, 2)) and (424 predecessor.denominator * m - predecessor.numerator * n <= 1):425 return __get_numerator_and_return_successor(426 __find_numerator_of_successor((m - predecessor.numerator + 1, m), predecessor), predecessor)427 else:428 ref_point = ceil((predecessor.numerator * (n - m) + 2) /429 (predecessor.denominator - predecessor.numerator))430 return __get_numerator_and_return_successor(431 __find_numerator_of_successor((ref_point - predecessor.numerator, ref_point - 1),432 predecessor), predecessor)433 else:434 if (predecessor > Fraction(1, 2)) or (predecessor.denominator * m - predecessor.numerator * n <= 1):435 return __get_numerator_and_return_successor(436 __find_numerator_of_successor((m - predecessor.numerator + 1, m), predecessor), predecessor)437 else:438 ref_point = ceil((predecessor.numerator * (n - m) + 2) /439 (predecessor.denominator - predecessor.numerator))440 return __get_numerator_and_return_successor(441 __find_numerator_of_successor((ref_point - predecessor.numerator, ref_point - 1),442 predecessor), predecessor)443444445def __get_numerator_and_return_predecessor(a: int, successor: Fraction) -> Fraction:446 return Fraction(a, (successor.denominator * a + 1) // successor.numerator)447448449def __get_numerator_and_return_successor(a: int, predecessor: Fraction) -> Fraction:450 return Fraction(a, (predecessor.denominator * a - 1) // predecessor.numerator)451452453def __find_numerator_of_predecessor(search_interval: Tuple(int, int), successor: Fraction) -> int:454 # Here we follow a suggestion found at https://code-maven.com/python-find-first-element-in-list-matching-condition455 return next(filter(lambda x: (successor.denominator * x + 1) % successor.numerator == 0,456 range(search_interval[0], search_interval[1] + 1)))457458459def __find_numerator_of_successor(search_interval: Tuple(int, int), predecessor: Fraction) -> int:460 # Here we follow a suggestion found at https://code-maven.com/python-find-first-element-in-list-matching-condition461 return next(filter(lambda x: (predecessor.denominator * x - 1) % predecessor.numerator == 0,462 range(search_interval[0], search_interval[1] + 1)))463464465def __predecessor_of_one_first_in_Fm(m: int) -> Fraction:466 return Fraction(m - 1, m)467 ...

Full Screen

Full Screen

method.py

Source:method.py Github

copy

Full Screen

1"""Functionality related to using a PEtab Select model selection method."""2import logging3from dataclasses import dataclass4from enum import Enum5from typing import Callable, Dict, List, Optional, Tuple, Union6import numpy as np7import petab_select8from petab_select import (9 VIRTUAL_INITIAL_MODEL,10 CandidateSpace,11 Criterion,12 Method,13 Model,14)15from ..C import TYPE_POSTPROCESSOR16from .model_problem import ModelProblem17class MethodSignalProceed(str, Enum):18 """Indicators for how a model selection method should proceed."""19 # TODO move to PEtab Select?20 STOP = 'stop'21 CONTINUE = 'continue'22@dataclass23class MethodSignal:24 """The state of a model selection method after a single model calibration.25 Attributes26 ----------27 accept:28 Whether to accept the model.29 proceed:30 How the method should proceed.31 """32 accept: bool33 # TODO change to bool?34 proceed: MethodSignalProceed35class MethodLogger:36 """Log results from a model selection method.37 Attributes38 ----------39 column_width:40 The width of columns when logging.41 column_sep:42 The substring used to separate column values when logging.43 level:44 The logging level.45 logger:46 A logger from the `logging` module.47 """48 column_width: int = 1249 column_sep: str = " | "50 def __init__(self, level: str = 'info'):51 self.logger = logging.getLogger(__name__)52 self.level = level53 def log(self, message, level: str = None) -> None:54 """Log a message.55 Parameters56 ----------57 message:58 The message.59 level:60 The logging level. Defaults to the value defined in the61 constructor.62 """63 if level is None:64 level = self.level65 getattr(self.logger, level)(message)66 def new_selection(self) -> None:67 """Start logging a new model selection."""68 padding = 2069 self.log('-' * padding + 'New Selection' + '-' * padding)70 columns = {71 "Predecessor model subspace:ID": "model0",72 "Model subspace:ID": "model",73 "Criterion ID": "crit",74 "Predecessor model criterion": "model0_crit",75 "Model criterion": "model_crit",76 "Criterion difference": "crit_diff",77 "Accept": "accept",78 }79 columns = {80 k: v.ljust(self.column_width)[: self.column_width]81 for k, v in columns.items()82 }83 self.log(self.column_sep.join(columns.values()))84 def new_result(85 self,86 accept,87 criterion,88 model,89 predecessor_model,90 max_id_length: str = 12,91 precision: int = 3,92 ) -> None:93 """Log a model calibration result.94 Parameters95 ----------96 accept:97 Whether the model is accepted.98 criterion:99 The criterion type.100 max_id_length:101 Model and predecessor model IDs are truncated to this length in the102 logged message.103 model:104 The calibrated model.105 predecessor_model:106 The predecessor model.107 precision:108 The number of decimal places to log.109 """110 model_criterion = model.get_criterion(criterion)111 def get_model_id(model: Model) -> str:112 """Get a model ID for logging.113 Parameters114 ----------115 model:116 The model.117 Returns118 -------119 str120 The ID.121 """122 model_subspace_id = model.model_subspace_id or ''123 original_model_id = model.model_id or model.get_hash()124 model_id = model_subspace_id + ':' + original_model_id125 return model_id126 def float_to_str(value: float, precision: int = 3) -> str:127 return f"{value:.{precision}e}"128 if isinstance(predecessor_model, Model):129 predecessor_model_id = get_model_id(predecessor_model)130 predecessor_model_criterion = predecessor_model.get_criterion(131 criterion132 )133 criterion_difference = float_to_str(134 model_criterion - predecessor_model_criterion135 )136 predecessor_model_criterion = float_to_str(137 predecessor_model_criterion138 )139 else:140 criterion_difference = None141 predecessor_model_criterion = None142 predecessor_model_id = predecessor_model143 model_criterion = float_to_str(model_criterion)144 message_parts = [145 predecessor_model_id,146 get_model_id(model),147 criterion.value,148 predecessor_model_criterion,149 model_criterion,150 criterion_difference,151 accept,152 ]153 message = self.column_sep.join(154 [155 str(v).ljust(self.column_width)[: self.column_width]156 for v in message_parts157 ]158 )159 self.log(message)160class MethodCaller:161 """Handle calls to PEtab Select model selection methods.162 Attributes163 ----------164 petab_select_problem:165 The PEtab Select problem.166 candidate_space:167 A `petab_select.CandidateSpace`, used to generate candidate models.168 criterion:169 The criterion by which models will be compared.170 criterion_threshold:171 The minimum improvement in criterion that a test model must have to172 be selected. The comparison is made according to the method. For173 example, in `ForwardSelector`, test models are compared to the174 previously selected model.175 history:176 The history of the model selection, as a `dict` with model hashes177 as keys and models as values.178 limit:179 Limit the number of calibrated models. NB: the number of accepted180 models may (likely) be fewer.181 logger:182 A `MethodLogger`, used to log results.183 minimize_options:184 A dictionary that will be passed to `pypesto.minimize` as keyword185 arguments for model optimization.186 model_postprocessor:187 A method that is applied to each model after calibration.188 objective_customizer:189 A method that is applied to the pyPESTO objective after the190 objective is initialized, before calibration.191 predecessor_model:192 Specify the predecessor (initial) model for the model selection193 algorithm. If `None`, then the algorithm will generate an194 predecessor model if required.195 select_first_improvement:196 If `True`, model selection will terminate as soon as a better model197 is found. If `False`, all candidate models will be tested.198 startpoint_latest_mle:199 If `True`, one of the startpoints in the multistart optimization200 will be the MLE of the latest model.201 """202 def __init__(203 self,204 petab_select_problem: petab_select.Problem,205 history: Dict[str, Model],206 # Arguments/attributes that can simply take the default value here.207 criterion_threshold: float = 0.0,208 limit: int = np.inf,209 minimize_options: Dict = None,210 model_postprocessor: TYPE_POSTPROCESSOR = None,211 objective_customizer: Callable = None,212 select_first_improvement: bool = False,213 startpoint_latest_mle: bool = True,214 # Arguments/attributes that should be handled more carefully.215 candidate_space: CandidateSpace = None,216 criterion: Criterion = None,217 # TODO misleading, `Method` here is simply an Enum, not a callable...218 method: Method = None,219 predecessor_model: Model = None,220 ):221 """Arguments are used in every `__call__`, unless overridden."""222 self.petab_select_problem = petab_select_problem223 self.history = history224 self.criterion_threshold = criterion_threshold225 self.limit = limit226 self.minimize_options = minimize_options227 self.model_postprocessor = model_postprocessor228 self.objective_customizer = objective_customizer229 self.predecessor_model = predecessor_model230 self.select_first_improvement = select_first_improvement231 self.startpoint_latest_mle = startpoint_latest_mle232 self.criterion = criterion233 if self.criterion is None:234 self.criterion = self.petab_select_problem.criterion235 # Forbid specification of both a candidate space and a method.236 if candidate_space is not None and method is not None:237 self.logger.log(238 (239 'Both `candidate_space` and `method` were provided. '240 'Please only provide one. The method will be ignored here.'241 ),242 level='warning',243 )244 # Get method.245 self.method = (246 method247 if method is not None248 else candidate_space.method249 if candidate_space is not None250 else self.petab_select_problem.method251 )252 # Require either a candidate space or a method.253 if candidate_space is None and self.method is None:254 raise ValueError(255 'Please provide one of either `candidate_space` or `method`, '256 'or specify the `method` in the PEtab Select problem.'257 )258 # Use candidate space if provided.259 if candidate_space is not None:260 self.candidate_space = candidate_space261 if predecessor_model is not None:262 candidate_space.set_predecessor_model(predecessor_model)263 # Else generate one based on the PEtab Select problem.264 else:265 self.candidate_space = (266 self.petab_select_problem.new_candidate_space(267 method=self.method,268 predecessor_model=self.predecessor_model,269 )270 )271 # May have changed from `None` to `petab_select.VIRTUAL_INITIAL_MODEL`272 self.predecessor_model = self.candidate_space.get_predecessor_model()273 self.logger = MethodLogger()274 def __call__(275 self,276 predecessor_model: Optional[Union[Model, None]] = None,277 ) -> Tuple[List[Model], Dict[str, Model]]:278 """Run a single iteration of the model selection method.279 A single iteration here refers to calibration of all candidate models.280 For example, given a predecessor model with 3 estimated parameters,281 with the forward method, a single iteration would involve calibration282 of all models that have both: the same 3 estimated parameters; and 1283 additional estimated paramenter.284 Parameters285 ----------286 predecessor_model:287 The model that will be used for comparison. Example 1: the288 initial model of a forward method. Example 2: all models found289 with a brute force method should be better than this model.290 Returns291 -------292 tuple293 A 2-tuple, with the following values:294 1. the best model; and295 2. all candidate models in this iteration, as a `dict` with296 model hashes as keys and models as values.297 """298 # Calibrated models in this iteration that improve on the predecessor299 # model.300 better_models = []301 # All calibrated models in this iteration (see second return value).302 local_history = {}303 self.logger.new_selection()304 if predecessor_model is None:305 # May still be `None` (e.g. brute force method)306 predecessor_model = self.predecessor_model307 candidate_models = petab_select.ui.candidates(308 problem=self.petab_select_problem,309 candidate_space=self.candidate_space,310 limit=self.limit,311 excluded_model_hashes=list(self.history),312 predecessor_model=predecessor_model,313 ).models314 if not candidate_models:315 raise StopIteration("No valid models found.")316 # TODO parallelize calibration (maybe not sensible if317 # `self.select_first_improvement`)318 for candidate_model in candidate_models:319 # autoruns calibration320 self.new_model_problem(model=candidate_model)321 local_history[candidate_model.model_id] = candidate_model322 method_signal = self.handle_calibrated_model(323 model=candidate_model,324 predecessor_model=predecessor_model,325 )326 if method_signal.accept:327 better_models.append(candidate_model)328 if method_signal.proceed == MethodSignalProceed.STOP:329 break330 self.history.update(local_history)331 best_model = None332 if better_models:333 best_model = petab_select.ui.best(334 problem=self.petab_select_problem,335 models=better_models,336 criterion=self.criterion,337 )338 return best_model, local_history339 def handle_calibrated_model(340 self,341 model: Model,342 predecessor_model: Optional[Model],343 ) -> MethodSignal:344 """Handle the model selection method, given a new calibrated model.345 Parameters346 ----------347 model:348 The calibrated model.349 predecessor_model:350 The predecessor model.351 Returns352 -------353 MethodSignal354 A `MethodSignal` that describes the result.355 """356 # Use the predecessor model from `__init__` if an iteration-specific357 # predecessor model was not supplied to `__call__`.358 if predecessor_model is None:359 # May still be `None` after this assignment.360 predecessor_model = self.predecessor_model361 # Default to accepting the model and continuing the method.362 method_signal = MethodSignal(363 accept=True,364 proceed=MethodSignalProceed.CONTINUE,365 )366 # Reject the model if it doesn't improve on the predecessor model.367 if (368 predecessor_model is not None369 and predecessor_model != VIRTUAL_INITIAL_MODEL370 and not self.model1_gt_model0(371 model1=model, model0=predecessor_model372 )373 ):374 method_signal.accept = False375 # Stop the model selection method if it a first improvement is found.376 if self.select_first_improvement and method_signal.accept:377 method_signal.proceed = MethodSignalProceed.STOP378 # TODO allow users to supply an arbitrary constraint function to e.g.:379 # - quit after 10 accepted models380 # - reject models that are worse than the current 10 best models381 # Log result382 self.logger.new_result(383 accept=method_signal.accept,384 criterion=self.criterion,385 model=model,386 predecessor_model=predecessor_model,387 )388 return method_signal389 def model1_gt_model0(390 self,391 model1: Model,392 model0: Model,393 ) -> bool:394 """Compare models by criterion.395 Parameters396 ----------397 model1:398 The new model.399 model0:400 The original model.401 Returns402 -------403 bool404 `True`, if `model1` is superior to `model0` by the criterion,405 else `False`.406 """407 if self.criterion in [408 Criterion.AIC,409 Criterion.AICC,410 Criterion.BIC,411 Criterion.LH,412 Criterion.LLH,413 Criterion.NLLH,414 ]:415 result = petab_select.model.default_compare(416 model0=model0,417 model1=model1,418 criterion=self.criterion,419 criterion_threshold=self.criterion_threshold,420 )421 else:422 raise NotImplementedError(423 f"Model selection criterion: {self.criterion}."424 )425 return result426 def new_model_problem(427 self,428 model: Model,429 valid: bool = True,430 autorun: bool = True,431 ) -> ModelProblem:432 """Create a model problem, usually to calibrate a model.433 Parameters434 ----------435 model:436 The model.437 valid:438 Whether the model should be considered a valid model. If it is439 not valid, it will not be calibrated.440 autorun:441 Whether the model should be calibrated upon creation.442 Returns443 -------444 ModelProblem445 The model selection problem.446 """447 x_guess = None448 if (449 self.startpoint_latest_mle450 and model.predecessor_model_hash in self.history451 ):452 predecessor_model = self.history[model.predecessor_model_hash]453 if str(model.petab_yaml) != str(predecessor_model.petab_yaml):454 raise NotImplementedError(455 'The PEtab YAML files differ between the model and its '456 'predecessor model. This may imply different (fixed union '457 'estimated) parameter sets. Support for this is not yet '458 'implemented.'459 )460 x_guess = {461 **predecessor_model.parameters,462 **predecessor_model.estimated_parameters,463 }464 return ModelProblem(465 model=model,466 criterion=self.criterion,467 valid=valid,468 autorun=autorun,469 x_guess=x_guess,470 minimize_options=self.minimize_options,471 objective_customizer=self.objective_customizer,472 postprocessor=self.model_postprocessor,...

Full Screen

Full Screen

ForkTree.py

Source:ForkTree.py Github

copy

Full Screen

2 def __init__(self, predecessor, data):3 self.predecessor = predecessor4 self.data = data5 self.sucessor = []6 def getpredecessor(self):7 return self.predecessor8 def setpredecessor(self, predecessor):9 self.predecessor = predecessor10 return predecessor11 def addsuccessor(self, sucessor):12 if isinstance(sucessor, Node):13 self.sucessor.append(sucessor)14 return 115 return 016 def getsuccessors(self):17 return self.sucessor18 def testsuccessor(self):19 if self.sucessor:20 return 121 return 022 def removesucessor(self, successor):23 if self.sucessor:24 return self.sucessor.remove(successor)25 else:26 return 027 def getdata(self):28 return self.data29class ForkTree:30 def __init__(self):31 self.Tree = []32 self.curNode = 033 def gettreenodecontent(self):34 ret = []35 for node in self.Tree:36 ret.append(node.getdata())37 return ret38 def getcurnode(self):39 return self.curNode40 def getcurnodepre(self):41 return self.curNode.getpredecessor()42 def getbasenode(self):43 for indsel in range(0, len(self.Tree)):44 found = 045 predecessor = self.Tree[indsel].getpredecessor()46 for indent in range(0, len(self.Tree)):47 if indsel != indent and predecessor == self.Tree[indent]:48 found = 149 break50 if not found:51 return predecessor52 return 053 def popcurnode(self):54 self.curNode = self.getcurnodepre()55 return self.curNode56 def popdelcurnode(self, curnode):57 prenode = self.popcurnode()58 self.Tree.remove(curnode)59 if prenode:60 prenode.removesucessor(curnode)61 return prenode62 def insertnode(self, data, prenode=0):63 if not prenode:64 node = self.curNode65 else:66 node = prenode67 newnode = Node(node, data)68 self.Tree.append(newnode)69 if node and self.curNode:70 self.curNode.addsuccessor(newnode)71 self.curNode = newnode72 return newnode73 def appendnodes(self, nodes, predecessor):74 if predecessor and predecessor not in self.Tree:75 return 076 for entry in nodes:77 entry.setpredecessor(predecessor)78 self.Tree.append(entry)79 if predecessor:80 predecessor.addsuccessor(entry)81 self.curNode = entry82 return self.curNode83 def appenddata(self, data, predecessor):84 nodes = []85 if predecessor and predecessor not in self.Tree:86 return 087 for entry in data:88 node = Node(predecessor, entry)89 nodes.append(node)90 self.Tree.append(node)91 if predecessor:92 predecessor.addsuccessor(node)93 return nodes94 def getpredecessor(self):95 self.curNode = self.curNode.getpredecessor()96 return self.curNode97 def getnodeandchilds(self):98 childs = self.curNode.getsuccessors()99 nodes = [self.curNode]100 while childs:101 newchilds = []102 for entry in childs:103 nodes.append(entry)104 newchilds += entry.getsuccessors()105 childs = newchilds106 return nodes107 def getchildnodes(self, curnode):108 children = [curnode]109 successors = curnode.getsuccessors()110 while successors:111 nextsuc = []112 for entry in successors:113 children.append(entry)114 nextsuc += entry.getsuccessors()115 if not nextsuc:116 return children117 successors = nextsuc118 return children119 def getendnodes(self):120 endnodes = []121 for entry in self.Tree:122 if not entry.testsuccessor():123 endnodes.append(entry)124 return endnodes125 def gettraces(self):126 traces = []127 endnodes = self.getendnodes()128 for endnode in endnodes:129 node = endnode130 trace = [node.getdata()]131 while node.getpredecessor():132 node = node.getpredecessor()133 trace.append(node.getdata())134 traces.append(trace)135 return traces136 def treetoarray(self):137 # Get end nodes138 endnodes = []139 for entry in self.Tree:140 if entry.testsuccessor():141 endnodes.append(entry)142 ret = []143 for entry in endnodes:144 curcond = []145 curcond += entry.getdata()146 predecessor = entry.getpredecessor()147 # Search backwards for predecessor148 while predecessor:149 curcond += predecessor.getdata()150 predecessor = predecessor.getpredecessor()151 ret.append(curcond)152 # Print all generated transactions153 def treetolist(self):154 ret = []155 for entry in self.Tree:156 ret.append(entry.getdata())...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run avocado automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful