Coverage for skema/program_analysis/matlab2cast.py: 29%

38 statements  

« prev     ^ index     » next       coverage.py v7.5.0, created at 2024-04-30 17:15 +0000

1import os 

2import sys 

3import json 

4import argparse 

5 

6from skema.program_analysis.CAST2FN.cast import CAST 

7from skema.program_analysis.CAST2FN.visitors.cast_to_agraph_visitor import ( 

8 CASTToAGraphVisitor, 

9) 

10 

11from skema.program_analysis.CAST.matlab.matlab_to_cast import MatlabToCast 

12 

13from typing import Optional 

14 

15def get_args(): 

16 parser = argparse.ArgumentParser( 

17 "Runs MATLAB to CAST pipeline on input MATLAB source file." 

18 ) 

19 parser.add_argument( 

20 "--rawjson", 

21 help="Dumps out raw JSON contents to stdout", 

22 action="store_true", 

23 ) 

24 parser.add_argument( 

25 "--stdout", 

26 help="Dumps CAST JSON to stdout instead of a file", 

27 action="store_true", 

28 ) 

29 parser.add_argument( 

30 "--agraph", 

31 help="Generates visualization of CAST as a PDF file", 

32 action="store_true", 

33 ) 

34 parser.add_argument("input_path", help="input MATLAB source file") 

35 options = parser.parse_args() 

36 return options 

37 

38 

39def matlab_to_cast( 

40 input_path, 

41 agraph=False, 

42 std_out=False, 

43 rawjson=False, 

44 cast_obj=False, 

45) -> Optional[CAST]: 

46 """Create a CAST object from a MATLAB file and serialize it to JSON. 

47 

48 Args: 

49 input_path: Path to the MATLAB source file 

50 agraph: If true, a PDF visualization of the graph is created. 

51 astprint: View the AST using the astpp module. 

52 std_out: If true, the CAST JSON is printed to stdout instead 

53 of written to a file. 

54 rawjson: If true, the raw JSON contents are printed to stdout. 

55 cast_obj: If true, returns the CAST as an object instead of printing to 

56 stdout. 

57 

58 Returns: 

59 If cast_obj is set to True, returns the CAST as an object. Else, 

60 returns None. 

61 """ 

62 

63 

64 out_cast = MatlabToCast(source_path = input_path).out_cast 

65 

66 file_name = os.path.basename(input_path) 

67 if agraph: 

68 V = CASTToAGraphVisitor(out_cast) 

69 last_slash_idx = file_name.rfind("/") 

70 file_ending_idx = file_name.rfind(".") 

71 pdf_file_name = ( 

72 f"{file_name[last_slash_idx + 1 : file_ending_idx]}.pdf" 

73 ) 

74 V.to_pdf(pdf_file_name) 

75 

76 # Then, print CAST as JSON 

77 if cast_obj: 

78 return out_cast 

79 else: 

80 if rawjson: 

81 print( 

82 json.dumps( 

83 out_cast.to_json_object(), sort_keys=True, indent=None 

84 ) 

85 ) 

86 else: 

87 if std_out: 

88 print(out_cast.to_json_str()) 

89 else: 

90 out_name = file_name.split(".")[0] 

91 print("Writing CAST to " + out_name + "--CAST.json") 

92 out_handle = open(out_name + "--CAST.json", "w") 

93 out_handle.write(out_cast.to_json_str()) 

94 

95if __name__ == "__main__": 

96 args = get_args() 

97 matlab_to_cast( 

98 args.input_path, 

99 args.agraph, 

100 args.stdout, 

101 args.rawjson, 

102 )