Coverage for moptipyapps / prodsched / instances.py: 100%

34 statements  

« prev     ^ index     » next       coverage.py v7.13.0, created at 2025-12-11 04:40 +0000

1""" 

2Generate instances for training and testing. 

3 

4In this package, we provide a function for generating instances in a 

5deterministic fashion for training and testing of MFC scenarios. 

6 

7The function :func:`get_instances` will return a fixed set of instances 

8for a given instance number. It allows you to store and retrieve compatible 

9instance sets of different sizes from a given directory. 

10It is not very efficient, but it will do. 

11 

12>>> from pycommons.io.temp import temp_dir 

13>>> with temp_dir() as td: 

14... inst_1 = get_instances(3, td) 

15... inst_2 = get_instances(1, td) 

16... inst_3 = get_instances(5, td) 

17 

18>>> len(inst_1) 

193 

20>>> len(inst_2) 

211 

22>>> len(inst_3) 

235 

24 

25>>> all(ix in inst_1 for ix in inst_2) 

26True 

27>>> all(ix in inst_3 for ix in inst_1) 

28True 

29""" 

30 

31from typing import Final 

32 

33from moptipy.utils.nputils import rand_seeds_from_str 

34from pycommons.io.path import Path 

35from pycommons.types import check_int_range 

36 

37from moptipyapps.prodsched.instance import ( 

38 Instance, 

39 instance_sort_key, 

40 load_instances, 

41 store_instances, 

42) 

43from moptipyapps.prodsched.mfc_generator import ( 

44 INFO_RAND_SEED, 

45 sample_mfc_instance, 

46) 

47 

48 

49def get_instances(n: int, inst_dir: str) -> tuple[Instance, ...]: 

50 """ 

51 Get the instances for the experiment. 

52 

53 :param n: the expected number of instances 

54 :param inst_dir: the instance directory 

55 """ 

56 check_int_range(n, "n", 1, 1_000_000) 

57 use_dir: Final[Path] = Path(inst_dir) 

58 

59 has_instances: bool = False 

60 if use_dir.exists(): 

61 try: 

62 has_instances = next(use_dir.list_dir(True, False)).endswith( 

63 ".txt") 

64 except StopIteration: 

65 has_instances = False 

66 

67 seeds: Final[list[int]] = rand_seeds_from_str("mfc", n) 

68 insts: Final[list[Instance]] = [] 

69 newly: Final[list[Instance]] = [] 

70 

71 if has_instances: 

72 for inst in load_instances(use_dir): 

73 if INFO_RAND_SEED in inst.infos: 

74 seed = int(inst.infos[INFO_RAND_SEED], 16) 

75 if seed in seeds: 

76 insts.append(inst) 

77 seeds.remove(seed) 

78 

79 for seed in seeds: 

80 inst = sample_mfc_instance(seed=seed) 

81 newly.append(inst) 

82 insts.append(inst) 

83 

84 insts.sort(key=instance_sort_key) 

85 if list.__len__(newly) > 0: 

86 newly.sort(key=instance_sort_key) 

87 store_instances(use_dir, newly) 

88 return tuple(insts)