pygx.geno¶
Program genome and genotypes.
geno
¶
Program genome and genotypes.
A program genome (pg.DNA) encodes the decisions that
generate a concrete object from a search space. Genotypes
(pygx.DNASpec) are the specifications of how to generate
them. Genotypes are separated from their corresponding hyper values
(pygx.HyperValue), which generate the client-side
objects, so that the algorithms that generate genomes are decoupled from the
programs that consume them. As a result, the same algorithm can be applied to
different user programs for optimization.
classDiagram
DNASpec <|-- Space
DNASpec <|-- DecisionPoint
Space *-- DecisionPoint : elements
DecisionPoint <|-- Choices
Choices *-- Space : candidates
DecisionPoint <|-- Float
DecisionPoint <|-- CustomDecisionPoint
DNA *-- DNA : children
DNA --> DNASpec : spec
Genotypes map 1:1 to hyper primitives as the following:
DNA
¶
DNA(
value: None | int | float | str | list[Any] | tuple[Any] = None,
children: list[DNA] | None = None,
spec: DNASpec | None = None,
metadata: dict[str, Any] | None = None,
*,
allow_partial: bool = False,
**kwargs: Any
)
Bases: Object
The genome of a symbolic object relative to its search space.
DNA is a hierarchical structure - each DNA node has a value, and a list of
child DNA nodes. The root node represents the genome that encodes an entire
object relative to its space. The value of a DNA node could be None, an
integer, a float number or a string, depending on its specification
(pg.DNASpec). A valid DNA has a form of the following.
| Hyper value type (DNASpec type) | Possible values | Child nodes |
|---|---|---|
pg.hyper.ObjectTemplate (pg.geno.Space) |
None (elements > 1) |
DNA of child decision points (Choices/Float) in the template. |
| " | None (elements == 1 and elements[0] num_choices > 1) |
Children of elements[0] |
| " | int (elements == 1 and elements[0] num_choices == 1) |
Children of the chosen candidate of elements[0] |
| " | float (elements == 1 and elements[0] is geno.Float) |
Empty |
pg.oneof (pg.geno.Choices) |
int (candidate index as choice) |
Children of Space for the chosen candidate |
pg.manyof (pg.geno.Choices) |
None (num_choices > 1) |
DNA of each chosen candidate |
| " | int (num_choices == 1) |
Children of chosen candidate |
pg.floatv (pg.geno.Float) |
float |
Empty |
pg.hyper.CustomHyper (pg.geno.CustomDecisionPoint) |
str (serialized object) |
User defined. |
DNA can also be represented in a compact form - a tree of numbers/strs, formally defined as:
<dna> := empty | <decision>
<decision> := <single-decision>
| <multiple-decisions>
| <conditional-choice>
<single-decision> := <categorical-decision>
| <float-decision>
| <custom-decision>
<categorical-decision> := int
<float-decision> := float
<custom-decision> := str
<multiple-decisions> := [<decision>, <decision>, ...]
<conditional-choice> := (<categorical-decision>,
<categorical-decision>,
...
<decision>)
Thus DNA can be constructed by nested structures of list, tuple and numbers. The numeric value for DNA can be integer (as index of choice) or float (the value itself will be used as decoded value).
Examples:
# Empty DNA. This may be generated by an empty template.
DNA()
# A DNA of a nested choice of depth 3: tuple items chain
# conditional decisions (0 -> 0 -> 0).
DNA((0, 0, 0))
# A DNA of three choices at the same level,
# positioned at 0, 1, 2, each choice has value 0.
DNA([0, 0, 0])
# A DNA of two choices (one two-level conditional,
# one non-conditional), position 0 is with choice path: 0 -> [0, 1],
# while [0, 1] means it's a multi-choice (e.g. `pg.manyof(2, ...)`).
# position 1 is a single non-conditional choice: 0.
DNA([(0, [0, 1]), 0])
# A DNA with custom decision point whose encoding
# is defined by the user.
DNA('abc')
Constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
None | int | float | str | list[Any] | tuple[Any]
|
Value for current node. |
None
|
children
|
list[DNA] | None
|
Child DNA(s). |
None
|
spec
|
DNASpec | None
|
DNA spec that constrains current node. |
None
|
metadata
|
dict[str, Any] | None
|
Optional dict as controller metadata for the DNA. |
None
|
allow_partial
|
bool
|
If True, allow the object to be partial. |
False
|
**kwargs
|
Any
|
keyword arguments that will be passed through to symbolic.Object. |
{}
|
Source code in pygx/geno/_base.py
is_subchoice
property
¶
Returns True if current DNA is a subchoice of a multi-choice.
multi_choice_spec
property
¶
multi_choice_spec: Optional[DecisionPoint]
Returns the multi-choice spec for child DNAs.
Returns:
| Type | Description |
|---|---|
Optional[DecisionPoint]
|
If the children of this DNA are decisions of a multi-choice's subchoices, |
Optional[DecisionPoint]
|
return the multi-choice spec ( |
is_multi_choice_container
property
¶
Returns True if the children of this DNA are multi-choice subchoices.
literal_value
property
¶
Returns the literal value represented by current DNA.
Requires the DNA to be bound with a DNASpec. Leaf decisions render as
their literal value when the spec provides one, falling back to
'{index}/{num_candidates}' for choices without literal values.
Conditional decision chains are joined with ' -> ' (e.g.
'1/2 -> 0.5'), and sibling decisions form a list.
named_decisions
property
¶
Returns a dict of name to the named DNA in the sub-tree.
on_sym_bound
¶
set_metadata
¶
set_metadata(key: str, value: Any, cloneable: bool = False) -> DNA
Set metadata associated with a key.
Metadata associated with the DNA will be persisted and carried over across
processes, which is different from userdata. (See set_userdata for
more details.)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Key for the metadata. |
required |
value
|
Any
|
Value for the metadata. |
required |
cloneable
|
bool
|
If True, the key/value will be propagated during clone. |
False
|
Returns:
| Type | Description |
|---|---|
DNA
|
Self. |
Source code in pygx/geno/_base.py
set_userdata
¶
set_userdata(key: str, value: Any, cloneable: bool = False) -> DNA
Sets user data associated with a key.
User data associated with the DNA will live only within current process,
and is not carried over during serialization/deserialization, which is
different from DNA metadata. (See set_metadata for more details.)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Key of the user data. |
required |
value
|
Any
|
Value of the user data. |
required |
cloneable
|
bool
|
If True, the key/value will be carry over to the cloned DNA. |
False
|
Returns:
| Type | Description |
|---|---|
DNA
|
Self. |
Source code in pygx/geno/_base.py
use_spec
¶
Use a DNA spec for this node and children recursively.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
DNASpec
|
DNA spec. |
required |
Returns:
| Type | Description |
|---|---|
DNA
|
Self. |
Raises:
| Type | Description |
|---|---|
ValueError
|
current DNA tree does not conform to the DNA spec. |
Source code in pygx/geno/_base.py
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 | |
parse
classmethod
¶
parse(
json_value: int | float | str | list[Any] | tuple[Any] | None,
spec: DNASpec | None = None,
) -> DNA
Parse DNA from a nested structure of numbers.
Deprecated: use DNA.__init__ instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
json_value
|
int | float | str | list[Any] | tuple[Any] | None
|
A nested structure of numbers. |
required |
spec
|
DNASpec | None
|
DNA spec that will be applied to current DNA tree. |
None
|
Returns:
| Type | Description |
|---|---|
DNA
|
an instance of DNA object. |
Raises:
| Type | Description |
|---|---|
ValueError
|
Bad format for json_value or parsed DNA does not conform to the DNA spec. |
Source code in pygx/geno/_base.py
from_dict
classmethod
¶
from_dict(
dict_repr: dict[Any, Any],
dna_spec: DNASpec,
use_ints_as_literals: bool = False,
) -> DNA
Create a DNA from its dictionary representation.
Example:
spec = pg.geno.space([
pg.geno.oneof(
[pg.geno.constant(), pg.geno.constant()],
location='x', literal_values=['a', 'b']),
pg.geno.floatv(0.0, 1.0, location='y'),
])
# Values as candidate indices.
dna = pg.DNA.from_dict({'x': 1, 'y': 0.5}, spec)
assert dna == pg.DNA([1, 0.5])
# Values as literal values.
dna = pg.DNA.from_dict({'x': 'b', 'y': 0.5}, spec)
assert dna == pg.DNA([1, 0.5])
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dict_repr
|
dict[Any, Any]
|
The dictionary representation of the DNA. The keys should be either strings as the decision point ID/name or DNASpec objects. The values should be either numeric or literal values for the decisions. For inactive decisions, their ID/spec should either be absent from the dictionary, or use None as their values. |
required |
dna_spec
|
DNASpec
|
The DNASpec that applies to the DNA. |
required |
use_ints_as_literals
|
bool
|
If True, when an integer is encountered for a dictionary value, treat it as the literal value. Otherwise, always treat it as a candidate index. |
False
|
Returns:
| Type | Description |
|---|---|
DNA
|
A DNA object. |
Source code in pygx/geno/_base.py
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 | |
to_dict
¶
to_dict(
key_type: str = "id",
value_type: str = "value",
multi_choice_key: str = "subchoice",
include_inactive_decisions: bool = False,
filter_fn: Callable[[DecisionPoint], bool] | None = None,
) -> dict[
DecisionPoint | str,
Union[None, DNA, float, int, str, list[DNA], list[int], list[str]],
]
Returns the dict representation of current DNA.
Example:
spec = pg.geno.space([
pg.geno.oneof(
[pg.geno.constant(), pg.geno.constant()],
location='x', literal_values=['a', 'b']),
pg.geno.floatv(0.0, 1.0, location='y'),
])
dna = pg.DNA([1, 0.5], spec=spec)
assert dna.to_dict() == {'x': 1, 'y': 0.5}
assert dna.to_dict(value_type='literal') == {'x': 'b', 'y': 0.5}
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key_type
|
str
|
Key type in returned dictionary. Acceptable values are:
|
'id'
|
value_type
|
str
|
Value type for choices in returned dictionary. Acceptable values are:
|
'value'
|
multi_choice_key
|
str
|
'subchoice', 'parent', or 'both'. If 'subchoice', each subchoice will insert a key into the dict. If 'parent', subchoices of a multi-choice will share the parent spec as key, its value will be a list of decisions from the subchoices. If 'both', the dict will contain both the keys for subchoices and the key for the parent multi-choice. |
'subchoice'
|
include_inactive_decisions
|
bool
|
If True, inactive decisions from the search space will be added to the dict with value None. Otherwise they will be absent in the dict. |
False
|
filter_fn
|
Callable[[DecisionPoint], bool] | None
|
Decision point filter. If None, all the decision points will be included in the dict. Otherwise only the decision points that pass the filter (returns True) will be included. |
None
|
Returns:
| Type | Description |
|---|---|
dict[DecisionPoint | str, Union[None, DNA, float, int, str, list[DNA], list[int], list[str]]]
|
A dictionary of requested key type to value type mapped from the DNA. |
Raises:
| Type | Description |
|---|---|
ValueError
|
argument |
Source code in pygx/geno/_base.py
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 | |
from_numbers
classmethod
¶
Create a DNA from a flattened list of dna values.
The values are consumed by the decision points of dna_spec in DFS
order — the inverse of DNA.to_numbers(flatten=True).
Example:
spec = pg.geno.space([
pg.geno.oneof([pg.geno.constant(), pg.geno.constant()],
location='x'),
pg.geno.floatv(0.0, 1.0, location='y'),
])
dna = pg.DNA.from_numbers([1, 0.5], spec)
assert dna == pg.DNA([1, 0.5])
assert dna.to_numbers() == [1, 0.5]
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dna_values
|
list[int | float | str]
|
A list of DNA values. |
required |
dna_spec
|
DNASpec
|
DNASpec that interprets the dna values. |
required |
Returns:
| Type | Description |
|---|---|
DNA
|
A DNA object. |
Raises:
| Type | Description |
|---|---|
ValueError
|
The input is too short or too long for |
Source code in pygx/geno/_base.py
1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 | |
to_numbers
¶
to_numbers(
flatten: bool = True,
) -> list[int | float | str] | Nestable[int | float | str]
Returns a (maybe) nested structure of numbers as decisions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
flatten
|
bool
|
If True, the hierarchy of the numbers will not be preserved. Decisions will be returned as a flat list in DFS order. Otherwise, a nestable structure of numbers will be returned. |
True
|
Returns:
| Type | Description |
|---|---|
list[int | float | str] | Nestable[int | float | str]
|
A flat list or a hierarchical structure of numbers as the decisions made for each decision point. |
Source code in pygx/geno/_base.py
from_fn
classmethod
¶
from_fn(
dna_spec: DNASpec,
generator_fn: Callable[[DecisionPoint], Union[list[int], float, str, DNA]],
) -> DNA
Generate a DNA with user generator function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dna_spec
|
DNASpec
|
The DNASpec for the DNA. |
required |
generator_fn
|
Callable[[DecisionPoint], Union[list[int], float, str, DNA]]
|
A callable object with signature:
The decision_point is a
|
required |
Example:
spec = pg.geno.space([
pg.geno.oneof([pg.geno.constant(), pg.geno.constant()],
location='x'),
])
dna = pg.DNA.from_fn(spec, lambda decision_point: [0])
assert dna == pg.DNA(0)
Returns:
| Type | Description |
|---|---|
DNA
|
A DNA generated from the user function. |
Source code in pygx/geno/_base.py
1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 | |
sym_jsonify
¶
Convert DNA to JSON object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
compact
|
bool
|
Whether use compact form. If compact, the nested number structure in DNA.parse will be used, otherwise members will be rendered out as regular symbolic Object. |
True
|
type_info
|
bool
|
If True, type information will be included in output, otherwise
only the compact value is emitted (as a proper WireValue — tuples
in their |
True
|
**kwargs
|
Any
|
Keyword arguments that will be passed to symbolic.Object if compact is False. |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
JSON representation of DNA. |
Source code in pygx/geno/_base.py
from_json
classmethod
¶
from_json(
json_value: dict[str, Any],
*,
allow_partial: bool = False,
root_path: KeyPath | None = None,
**kwargs: Any
) -> DNA
Class method that load a DNA from a JSON value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
json_value
|
dict[str, Any]
|
Input JSON value, only JSON dict is acceptable. |
required |
allow_partial
|
bool
|
Whether to allow elements of the list to be partial. |
False
|
root_path
|
KeyPath | None
|
KeyPath of loaded object in its object tree. |
None
|
**kwargs
|
Any
|
Keyword arguments that will be passed to symbolic.from_json. |
{}
|
Returns:
| Type | Description |
|---|---|
DNA
|
A DNA object. |
Source code in pygx/geno/_base.py
get
¶
get(
key: Union[int, slice, str, KeyPath, DecisionPoint], default: Any = None
) -> Union[Any, None, DNA, list[Optional[DNA]]]
Get an immediate child DNA or DNA in the sub-tree.
Source code in pygx/geno/_base.py
iter_dna
¶
format
¶
format(
compact: bool = False,
verbose: bool = True,
root_indent: int = 0,
*,
list_wrap_threshold: int = 80,
as_dict: bool = False,
**kwargs
)
Customize format method for DNA for more compact representation.
Source code in pygx/geno/_base.py
parameters
¶
Returns parameters for this DNA to emit based on its spec.
Deprecated: use to_dict instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
use_literal_values
|
bool
|
If True, use literal values from DNASpec for Choices, otherwise returns '{choice}/{num_candidates} ({literal})'. Otherwise returns '{choice}/{num_candidates}'. |
False
|
Returns:
| Type | Description |
|---|---|
dict[str, str]
|
Dict of parameter names to their values mapped from this DNA. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the DNA is not bound with a DNASpec. |
Source code in pygx/geno/_base.py
from_parameters
classmethod
¶
from_parameters(
parameters: dict[str, Any],
dna_spec: DNASpec,
use_literal_values: bool = False,
) -> DNA
Create DNA from parameters based on DNASpec.
Deprecated: use from_dict instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameters
|
dict[str, Any]
|
A 1-depth dict of parameter names to parameter values. |
required |
dna_spec
|
DNASpec
|
DNASpec to interpret the parameters. |
required |
use_literal_values
|
bool
|
If True, integer decisions are interpreted as
literal values of the corresponding choice rather than candidate
indices. String decisions are always accepted as either literal
values or |
False
|
Returns:
| Type | Description |
|---|---|
DNA
|
DNA instance bound with the DNASpec. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If parameters are not aligned with DNA spec. |
Source code in pygx/geno/_base.py
AttributeDict
¶
Bases: dict
A dictionary that allows attribute access.
ConditionalKey
¶
Key used in pygx.KeyPath to represent conditional element.
A conditional key renders as =<index>/<num_choices>. For example,
a[=1/2].b identifies b under choice a when candidate 1 (out of 2)
is chosen, and a[0][=0/3].b identifies b under subchoice a[0] of a
multi-choice when its candidate 0 (out of 3) is chosen.
Source code in pygx/geno/_base.py
DecisionPoint
¶
DecisionPoint(
*,
allow_partial: bool = False,
sealed: bool | None = None,
root_path: KeyPath | None = None,
explicit_init: bool = False,
**kwargs: Any
)
Bases: DNASpec
Base class for decision points.
Child classes:
Source code in pygx/symbolic/_object.py
3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 | |
DNASpec
¶
DNASpec(
*,
allow_partial: bool = False,
sealed: bool | None = None,
root_path: KeyPath | None = None,
explicit_init: bool = False,
**kwargs: Any
)
Bases: Object
Base class for DNA specifications (genotypes).
A DNASpec object describes the rules and tips for generating a DNA. It has two families of subclasses:
pygx.geno.Space: Represents a space or sub-space, which contains a list of decision points.pygx.geno.DecisionPoint: Represents a concrete decision point.
Concrete decision points are the following:
pygx.geno.Choices: Represents a single categorical choice or multiple related categorical choices. Each candidate is a sub-space.pygx.geno.Float: Represents a continuous float value within a range.pygx.geno.CustomDecisionPoint: Represents the genotype for apygx.hyper.CustomHyper.
Every decision point carries hints as a reference for the DNA
generator to consume when generating values. Hints must be serializable
so they can be passed between clients and servers.
All DNASpec types also allow users to attach data via set_userdata.
User data is meant to be used within the same process only, thus is not
required to be serializable.
Source code in pygx/symbolic/_object.py
3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 | |
is_categorical
abstractmethod
property
¶
Returns True if current node is a categorical choice.
is_subchoice
abstractmethod
property
¶
Returns True if current node is a subchoice of a multi-choice.
is_numerical
abstractmethod
property
¶
Returns True if current node is numerical decision.
is_custom_decision_point
abstractmethod
property
¶
Returns True if current node is a custom decision point.
decision_points
abstractmethod
property
¶
decision_points: list[DecisionPoint]
Returns all decision points in their declaration order.
named_decision_points
property
¶
named_decision_points: dict[str, Union[DecisionPoint, list[DecisionPoint]]]
Returns all named decision points in their declaration order.
space_size
abstractmethod
property
¶
Returns the size of the search space, or -1 if infinite.
parent_choice
property
¶
parent_choice: Optional[DecisionPoint]
Returns the parent choice of current space.
id
property
¶
id: KeyPath
Returns a path of locations from the root as the ID for current node.
The ID is the canonical identifier of a decision point within its
search space. Locations under a chosen candidate are qualified by a
conditional key (see pg.geno.ConditionalKey), and subchoices of a
multi-choice are indexed by their position. For example, given:
spec = pg.geno.space([
pg.geno.oneof([
pg.geno.constant(),
pg.geno.space([pg.geno.floatv(0.1, 1.0, location='lr')]),
], location='model'),
pg.geno.manyof(
2, [pg.geno.constant(), pg.geno.constant(), pg.geno.constant()],
location='ops'),
])
the decision points have IDs model, model[=1/2].lr (the float
is active only when candidate 1 of 2 is chosen), ops[0] and
ops[1] (the two subchoices of the multi-choice).
on_sym_bound
¶
Event that is triggered when object is modified.
on_topo_path_change
¶
Event that is triggered when path changes.
Source code in pygx/geno/_base.py
first_dna
¶
first_dna(attach_spec: bool = True) -> DNA
Returns the first DNA in the space represented by this spec.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
attach_spec
|
bool
|
If True, current spec will be attached to the returned DNA. |
True
|
Returns:
| Type | Description |
|---|---|
DNA
|
The first DNA in enumeration order. |
Source code in pygx/geno/_base.py
next_dna
¶
Returns the next DNA in the space represented by this spec.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dna
|
Optional[DNA]
|
The DNA whose next will be returned. If None, |
None
|
attach_spec
|
bool
|
If True, current spec will be attached to the returned DNA. |
True
|
Returns:
| Type | Description |
|---|---|
Optional[DNA]
|
The next DNA or None if there is no next DNA. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
The (sub-)space is not enumerable - e.g. it
contains a |
Source code in pygx/geno/_base.py
random_dna
¶
random_dna(
random_generator: ModuleType | Random | None = None,
attach_spec: bool = True,
previous_dna: Optional[DNA] = None,
) -> DNA
Returns a random DNA based on current spec.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
random_generator
|
ModuleType | Random | None
|
An optional Random object. If None, the global random module will be used. |
None
|
attach_spec
|
bool
|
If True, current spec will be attached to the returned DNA. |
True
|
previous_dna
|
Optional[DNA]
|
An optional DNA representing previous DNA. This field might be useful for generating stateful random DNAs. |
None
|
Returns:
| Type | Description |
|---|---|
DNA
|
A random DNA based on current spec. |
Source code in pygx/geno/_base.py
iter_dna
¶
Iterate the DNA in the space represented by this spec.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dna
|
Optional[DNA]
|
An optional DNA as the start point (exclusive) for iteration. |
None
|
attach_spec
|
bool
|
If True, the DNASpec will be attached to the DNA returned. |
True
|
Yields:
| Type | Description |
|---|---|
DNA
|
The next DNA according to the spec. |
Source code in pygx/geno/_base.py
get
¶
get(
name_or_id: KeyPath | str, default: Any = None
) -> Union[DecisionPoint, list[DecisionPoint]]
Get decision point(s) by name or ID, with a default for misses.
Names are looked up first, then IDs. The subchoices of a multi-choice share the parent's ID, so an ID lookup on a multi-choice returns a list of decision points.
Example:
spec = pg.geno.space([
pg.geno.oneof(
[pg.geno.constant(), pg.geno.constant()],
location='x', name='x_choice'),
])
assert spec.get('x_choice') is spec.get('x')
assert spec.get('nope') is None
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name_or_id
|
KeyPath | str
|
The name or ID of the decision point(s) to look up. |
required |
default
|
Any
|
Value to return when no decision point matches. |
None
|
Returns:
| Type | Description |
|---|---|
Union[DecisionPoint, list[DecisionPoint]]
|
The matching decision point, a list of decision points (for the |
Union[DecisionPoint, list[DecisionPoint]]
|
subchoices of a multi-choice), or |
Source code in pygx/geno/_base.py
set_userdata
¶
Sets user data.
User data can be used for storing state associated with the DNASpec, and
is not persisted across processes or during serialization. Use hints to
carry persistent objects for the DNASpec.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Key of the user data. |
required |
value
|
Any
|
Value of the user data. |
required |
Source code in pygx/geno/_base.py
Choices
¶
Choices(num_choices: int = 1, *, candidates: list[Space], **kwargs)
Bases: DecisionPoint
Represents a single or multiple choices from a list of candidates.
Example:
# Create a single choice with a nested subspace for candidate 2 (0-based).
pg.geno.oneof([
pg.geno.constant(),
pg.geno.constant(),
pg.geno.space([
pg.geno.floatv(0.1, 1.0),
pg.geno.manyof(2, [
pg.geno.constant(),
pg.geno.constant(),
pg.geno.constant()
])
])
])
See also: pygx.geno.oneof, pygx.geno.manyof.
Source code in pygx/geno/_categorical.py
is_categorical
property
¶
Returns True if current node is a categorical choice.
is_subchoice
property
¶
Returns if current choice is a subchoice of a multi-choice.
is_custom_decision_point
property
¶
Returns True if current node is a custom decision point.
decision_points
property
¶
decision_points: list[DecisionPoint]
Returns all decision points in their declaration order.
Returns:
| Type | Description |
|---|---|
list[DecisionPoint]
|
All decision points in current space. For multi-choices, the sub-choice |
list[DecisionPoint]
|
objects will be returned. Users can call |
list[DecisionPoint]
|
sub-choice to access the parent multi-choice node. |
subchoice
¶
subchoice(index: int) -> Choices
Returns spec for choice i.
Source code in pygx/geno/_categorical.py
format_candidate
¶
Get a formatted candidate value by index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int
|
The index of the candidate to format. |
required |
display_format
|
str
|
One of 'choice', 'literal' and 'choice_and_literal' as the output format for human consumption. |
'choice_and_literal'
|
Returns:
| Type | Description |
|---|---|
str | int | float
|
A int, float or string that represent the candidate based on the display format. |
Source code in pygx/geno/_categorical.py
candidate_index
¶
Returns the candidate index of a choice value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
choice_value
|
str | int | float
|
Choice value can be:
a (integer, float or string) as a candidate's literal value,
or a text in the format " |
required |
Returns:
| Type | Description |
|---|---|
int
|
The index of chosen candidate. |
Raises:
| Type | Description |
|---|---|
ValueError
|
|
Source code in pygx/geno/_categorical.py
validate
¶
validate(dna: DNA) -> None
Validate whether a DNA value conforms to this spec.
Source code in pygx/geno/_categorical.py
format
¶
format(
compact: bool = True,
verbose: bool = True,
root_indent: int = 0,
show_id: bool = True,
**kwargs
)
Format this object.
Source code in pygx/geno/_categorical.py
CustomDecisionPoint
¶
CustomDecisionPoint(
*,
allow_partial: bool = False,
sealed: bool | None = None,
root_path: KeyPath | None = None,
explicit_init: bool = False,
**kwargs: Any
)
Bases: DecisionPoint
Represents a user-defined decision point.
It is the genotype for pygx.hyper.CustomHyper.
Its DNA value is a string whose encoding is defined by the user.
Example:
See also: pygx.geno.custom.
Source code in pygx/symbolic/_object.py
3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 | |
is_categorical
property
¶
Returns True if current node is a categorical choice.
is_subchoice
property
¶
Returns True if current node is a subchoice of a multi-choice.
is_custom_decision_point
property
¶
Returns True if current node is a custom decision point.
decision_points
property
¶
decision_points: list[DecisionPoint]
Returns all decision points in their declaration order.
validate
¶
validate(dna: DNA) -> None
Validate whether a DNA value conforms to this spec.
Source code in pygx/geno/_custom.py
sym_jsonify
¶
sym_jsonify(**kwargs: Any) -> WireValue
Overrides sym_jsonify to exclude non-serializable fields.
Source code in pygx/geno/_custom.py
format
¶
format(
compact: bool = True,
verbose: bool = True,
root_indent: int = 0,
show_id: bool = True,
**kwargs
)
Format this object.
Source code in pygx/geno/_custom.py
Deduping
¶
Deduping(generator: DNAGenerator, **kwargs)
Bases: DNAGenerator
Deduping generator.
A deduping generator can be applied on another generator to dedup its proposed DNAs.
Hash function
By default, the hash function is the symbolic hash of the DNA, which returns the same hash when the decisions from the DNA are the same.
For example:
will only generate unique DNAs. When hash_fn is specified, it allows the
user to compute the hash for a DNA.
For example:
will dedup based on the sum of all decision values.
If no novel DNA can be obtained within max_proposal_attempts inner
proposals, the generator stops (raises StopIteration).
Number of duplicates
An optional max_duplicates can be provided by the user to allow a few
duplicates.
For example:
Note: for inner DNAGenerators that require user feedback, duplication accounting is based on DNAs that are fed back to the DNAGenerator, not proposed ones.
Automatic reward computation
Automatic reward computation will be enabled when auto_reward_fn is
provided AND when the inner generator takes feedback. It allows users to
compute the reward for new duplicates (which exceed the max_duplicates
limit) by aggregating rewards from previous duplicates. Such DNAs will be
fed back to the DNAGenerator without client's evaluation (supported by
pg.sample through the 'reward' metadata).
For example:
pg.geno.Deduping(pg.algo.evolution.regularized_evolution(),
auto_reward_fn=lambda rs: sum(rs) / len(rs))
Source code in pygx/geno/_deduping.py
DNAGenerator
¶
DNAGenerator(
*,
allow_partial: bool = False,
sealed: bool | None = None,
root_path: KeyPath | None = None,
explicit_init: bool = False,
**kwargs: Any
)
Bases: Object
Base class for DNA generator.
A DNA generator is an object that produces pygx.DNA, and
optionally takes feedback from the caller to improve its future proposals.
To implement a DNA generator, the user must implement the _propose method,
and can optionally override the _setup, _feedback and _replay methods.
-
Making proposals (Required): This method defines what to return as the next DNA from the generator, users MUST override the
_proposemethod to implement this logic._proposecan raiseStopIterationwhen no more DNA can be produced. -
Custom setup (Optional): Usually a DNAGenerator subclass has its internal state, which can be initialized when the search space definition is attached to the DNAGenerator. To do so, the user can override the
_setupmethod, in which we can access the search space definition (DNASpec object) viaself.dna_spec. -
Taking feedback (Optional): A DNAGenerator may take feedback from the caller on the fitness of proposed DNA to improve future proposals. The fitness is measured by a reward (a float number as the measure of a single objective, or a tuple of float numbers as the measure for multiple objectives). The user should override the
_feedbackmethod to implement such logic. If the reward is for multiple objectives, the user should override themulti_objectiveproperty to return True. -
State recovery (Optional): DNAGenerator was designed with distributed computing in mind, in which a process can be preempted or killed unexpectedly. Therefore, a DNAGenerator should be able to recover its state from historical proposals and rewards. The
recovermethod was introduced for such purpose, whose default implementation is to replay the history through the_replaymethod (which calls_feedbackby default). If the user has custom replay logic other than_feedback, they should override the_replaymethod. In some use cases, the user may want to implement their own checkpointing logic. In such cases, the user can override therecovermethod as a no-op. As a side note, therecovermethod will be called by the tuning backend (pg.tuning) aftersetupbut beforepropose.
Example:
class MyGenerator(pg.geno.DNAGenerator):
def _setup(self):
# `self.dna_spec` is available once `setup` has been called.
self._rewards = []
def _propose(self):
return self.dna_spec.random_dna()
def _feedback(self, dna, reward):
self._rewards.append(reward)
search_space = pg.geno.space([
pg.geno.oneof([pg.geno.constant(), pg.geno.constant()])
])
generator = MyGenerator()
generator.setup(search_space)
# Since `MyGenerator` overrides `_feedback`, iteration yields a
# (DNA, feedback) tuple; feedback-free generators yield just the DNA.
for dna, feedback in generator:
feedback(1.0) # Report the reward for the proposed DNA.
break
See also:
Source code in pygx/symbolic/_object.py
3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 | |
multi_objective
property
¶
If True, current DNA generator supports multi-objective optimization.
needs_feedback
property
¶
Returns True if the DNAGenerator needs feedback.
This is detected by whether the subclass overrides _feedback.
setup
¶
setup(dna_spec: DNASpec) -> None
Set up the generator with a search space definition.
Must be called before propose, feedback or iteration. It resets
the proposal/feedback counters and invokes _setup for subclass
initialization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dna_spec
|
DNASpec
|
The DNASpec that defines the search space. |
required |
Source code in pygx/geno/_dna_generator.py
propose
¶
propose() -> DNA
Proposes a DNA to evaluate.
Returns:
| Type | Description |
|---|---|
DNA
|
The proposed DNA. |
Raises:
| Type | Description |
|---|---|
StopIteration
|
The generator cannot produce more DNAs. |
feedback
¶
feedback(dna: DNA, reward: float | tuple[float]) -> None
Feedback a completed trial to the algorithm.
When the generator does not need feedback (needs_feedback is
False), only the feedback counter is updated and _feedback is not
called.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dna
|
DNA
|
a DNA object. |
required |
reward
|
float | tuple[float]
|
reward for the DNA. It is a float if |
required |
Source code in pygx/geno/_dna_generator.py
recover
¶
recover(history: Iterable[tuple[DNA, None | float | tuple[float]]]) -> None
Recover states by replaying the proposal history.
NOTE: recover will always be called before first propose and could be
called multiple times if there are multiple source of history, e.g: trials
from a previous study and existing trials from current study.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
history
|
Iterable[tuple[DNA, None | float | tuple[float]]]
|
An iterable object that consists of historically proposed DNA with its reward. The reward will be None if it is not yet provided (via feedback). |
required |
Source code in pygx/geno/_dna_generator.py
Float
¶
Bases: DecisionPoint
Represents the genotype for a float-value genome.
Example:
See also: pygx.geno.floatv.
Source code in pygx/geno/_numerical.py
is_categorical
property
¶
Returns True if current node is a categorical choice.
is_subchoice
property
¶
Returns True if current node is a subchoice of a multi-choice.
is_custom_decision_point
property
¶
Returns True if current node is a custom decision point.
decision_points
property
¶
decision_points: list[DecisionPoint]
Returns all decision points in their declaration order.
on_sym_bound
¶
Custom logics to validate value.
Source code in pygx/geno/_numerical.py
validate
¶
validate(dna: DNA) -> None
Validate whether a DNA value conforms to this spec.
Source code in pygx/geno/_numerical.py
format
¶
format(
compact: bool = True,
verbose: bool = True,
root_indent: int = 0,
show_id: bool = True,
**kwargs
)
Format this object.
Source code in pygx/geno/_numerical.py
Random
¶
Bases: DNAGenerator
Random DNA generator.
Proposes uniformly random DNAs from the search space, independent of any
feedback. When seed is None, the global random module is used;
otherwise a dedicated random.Random(seed) is used, which makes the
proposal sequence reproducible - state recovery replays the sequence by
re-generating past proposals.
Example:
search_space = pg.geno.space([
pg.geno.oneof([pg.geno.constant(), pg.geno.constant()])
])
generator = pg.geno.Random(seed=1)
generator.setup(search_space)
dna = generator.propose()
Source code in pygx/geno/_random.py
Space
¶
Space(elements: list[DecisionPoint] | None = None, **kwargs)
Bases: DNASpec
Represents a search space that consists of a list of decision points.
Example:
# Create a constant space.
space = pg.geno.Space([])
# Create a space with one categorical decision point
# and a float decision point
space = pg.geno.space([
pg.geno.oneof([
pg.geno.constant(),
pg.geno.constant(),
]),
pg.geno.floatv(0.0, 1.0)
])
See also: pygx.geno.constant.
Source code in pygx/geno/_space.py
is_categorical
property
¶
Returns True if current node is a categorical choice.
is_subchoice
property
¶
Returns True if current node is a subchoice of a multi-choice.
is_custom_decision_point
property
¶
Returns True if current node is a custom decision point.
is_constant
property
¶
Returns whether this space is constant.
A constant Space does not have any decision points.
decision_points
property
¶
decision_points: list[DecisionPoint]
Returns all decision points in their declaration order.
validate
¶
validate(dna: DNA) -> None
Validate whether a DNA value conforms to this spec.
Source code in pygx/geno/_space.py
format
¶
Format this object.
Source code in pygx/geno/_space.py
Sweeping
¶
Sweeping(
*,
allow_partial: bool = False,
sealed: bool | None = None,
root_path: KeyPath | None = None,
explicit_init: bool = False,
**kwargs: Any
)
Bases: DNAGenerator
Sweeping (Grid Search) DNA generator.
Enumerates every DNA in the search space exactly once, in the
enumeration order defined by DNASpec.next_dna (last decision point
advances first). It takes no feedback, and raises StopIteration when
the space is exhausted, which ends iteration.
Example:
search_space = pg.geno.space([
pg.geno.oneof([pg.geno.constant(), pg.geno.constant()])
])
generator = pg.geno.Sweeping()
generator.setup(search_space)
print([str(dna) for dna in generator])
# ['DNA(0)', 'DNA(1)']
Note: spaces containing Float or custom decision points without a
next_dna_fn cannot be swept.
Source code in pygx/symbolic/_object.py
3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 | |
manyof
¶
manyof(
num_choices: int,
candidates: list[DNASpec],
distinct: bool = True,
sorted: bool = False,
literal_values: list[str | int | float] | None = None,
hints: Any = None,
location: str | KeyPath = KeyPath(),
name: str | None = None,
) -> Choices
Returns a multi-choice specification.
It creates the genotype for pygx.manyof.
Example:
spec = pg.geno.manyof(2, [
pg.geno.constant(),
pg.geno.constant(),
pg.geno.oneof([
pg.geno.constant(),
pg.geno.constant()
])
])
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_choices
|
int
|
Number of choices. |
required |
candidates
|
list[DNASpec]
|
A list of |
required |
distinct
|
bool
|
If True, the decisions for the multiple choices should be distinct from each other (based on the value of selected indices). |
True
|
sorted
|
bool
|
If True, the decisions returned should be sorted by the values of selected indices. |
False
|
literal_values
|
list[str | int | float] | None
|
An optional list of string, integer, or float as the literal values for the candidates for display purpose. |
None
|
hints
|
Any
|
An optional hint object. |
None
|
location
|
str | KeyPath
|
A |
KeyPath()
|
name
|
str | None
|
An optional global unique name for identifying this decision point. |
None
|
Returns:
| Type | Description |
|---|---|
Choices
|
A |
See also:
Source code in pygx/geno/_categorical.py
oneof
¶
oneof(
candidates: list[DNASpec],
literal_values: list[str | int | float] | None = None,
hints: Any = None,
location: str | KeyPath = KeyPath(),
name: str | None = None,
) -> Choices
Returns a single choice specification.
It creates the genotype for pygx.oneof.
Example:
spec = pg.geno.oneof([
pg.geno.constant(),
pg.geno.oneof([
pg.geno.constant(),
pg.geno.constant()
])
])
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
candidates
|
list[DNASpec]
|
A list of |
required |
literal_values
|
list[str | int | float] | None
|
An optional list of string, integer, or float as the literal values for the candidates for display purpose. |
None
|
hints
|
Any
|
An optional hint object. |
None
|
location
|
str | KeyPath
|
A |
KeyPath()
|
name
|
str | None
|
An optional global unique name for identifying this decision point. |
None
|
Returns:
| Type | Description |
|---|---|
Choices
|
A |
See also:
Source code in pygx/geno/_categorical.py
custom
¶
custom(
hyper_type: str | None = None,
next_dna_fn: Callable[[DNA | None], DNA | None] | None = None,
random_dna_fn: Callable[[Any, DNA | None], DNA] | None = None,
hints: Any = None,
location: KeyPath = KeyPath(),
name: str | None = None,
) -> CustomDecisionPoint
Returns a custom decision point.
It creates the genotype for subclasses of pygx.hyper.CustomHyper.
Example:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hyper_type
|
str | None
|
An optional display type for the custom decision point. |
None
|
next_dna_fn
|
Callable[[DNA | None], DNA | None] | None
|
An optional callable for computing the next DNA for current decision point. |
None
|
random_dna_fn
|
Callable[[Any, DNA | None], DNA] | None
|
An optional callable for computing a random DNA for current decision point. |
None
|
hints
|
Any
|
An optional hint object. |
None
|
location
|
KeyPath
|
A |
KeyPath()
|
name
|
str | None
|
An optional global unique name for identifying this decision point. |
None
|
Returns:
| Type | Description |
|---|---|
CustomDecisionPoint
|
A |
See also:
Source code in pygx/geno/_custom.py
dna_generator
¶
dna_generator(func: Callable[[DNASpec], Iterator[DNA]]) -> type[DNAGenerator]
Decorator that converts a generation function to a DNAGenerator class.
The decorated function takes the search space definition (a DNASpec) and
yields DNAs; each propose call pulls the next item from the iterator,
and exhausting the iterator ends the generator (StopIteration).
Example:
@pg.geno.dna_generator
def first_ten(dna_spec):
dna = None
for _ in range(10):
dna = dna_spec.next_dna(dna)
if dna is None:
break
yield dna
# The decorator returns a DNAGenerator subclass, which is instantiated
# with no arguments.
generator = first_ten()
generator.setup(pg.geno.space([
pg.geno.oneof([pg.geno.constant(), pg.geno.constant()])
]))
print([str(dna) for dna in generator])
# ['DNA(0)', 'DNA(1)']
Another example that reads DNAs from a file:
def from_file(filepath):
@pg.geno.dna_generator
def file_based_dna_generator(dna_spec):
dna_list = pg.load(filepath)
for dna in dna_list:
dna.use_spec(dna_spec)
yield dna
return file_based_dna_generator
See also: pygx.DNAGenerator
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable[[DNASpec], Iterator[DNA]]
|
the generation function in signature:
|
required |
Returns:
| Type | Description |
|---|---|
type[DNAGenerator]
|
A DNAGenerator class. |
Source code in pygx/geno/_dna_generator.py
floatv
¶
floatv(
min_value: float,
max_value: float,
scale: str | None = None,
hints: Any = None,
location: KeyPath = KeyPath(),
name: str | None = None,
) -> Float
Returns a Float specification.
It creates the genotype for pygx.floatv.
Example:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
min_value
|
float
|
The lower bound of decision. |
required |
max_value
|
float
|
The upper bound of decision. |
required |
scale
|
str | None
|
An optional string as the scale of the range. Supported values
are None, 'linear', 'log', and 'rlog'.
If None, the feasible space is unscaled.
If |
None
|
hints
|
Any
|
An optional hint object. |
None
|
location
|
KeyPath
|
A |
KeyPath()
|
name
|
str | None
|
An optional global unique name for identifying this decision point. |
None
|
Returns:
| Type | Description |
|---|---|
Float
|
A |
See also:
Source code in pygx/geno/_numerical.py
random_dna
¶
random_dna(
dna_spec: DNASpec,
random_generator: None | ModuleType | Random = None,
attach_spec: bool = True,
previous_dna: DNA | None = None,
) -> DNA
Generates a random DNA from a DNASpec.
Example:
spec = pg.geno.space([
pg.geno.oneof([
pg.geno.constant(),
pg.geno.constant(),
pg.geno.constant()
]),
pg.geno.floatv(0.1, 0.2)
])
print(pg.random_dna(spec))
# Example output: DNA([1, 0.18935385454561734])
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dna_spec
|
DNASpec
|
a DNASpec object. |
required |
random_generator
|
None | ModuleType | Random
|
a Python random generator. |
None
|
attach_spec
|
bool
|
If True, attach the DNASpec to generated DNA. |
True
|
previous_dna
|
DNA | None
|
An optional DNA representing previous DNA. This field might be useful for generating stateful random DNAs. |
None
|
Returns:
| Type | Description |
|---|---|
DNA
|
A DNA object. |
Source code in pygx/geno/_random.py
constant
¶
constant() -> Space
Returns a constant candidate (an empty space) for Choices.
Example:
Returns:
| Type | Description |
|---|---|
Space
|
a constant |
See also:
Source code in pygx/geno/_space.py
options: show_root_heading: false show_root_toc_entry: false members_order: source heading_level: 2