################################################################################
#                                                                              #
# Name: VDMML_PYTHON_API_ACCESS.TXT                                            #
#                                                                              #
# Purpose: Example script for API access to SAS® VDMML using PYTHON            #
#                                                                              #
# History: 7July2022 File Created.                                             #
#                                                                              #
# Copyright(c) 2022 SAS Institute Inc., Cary, NC, USA. All Rights Reserved.    #
#                                                                              #
################################################################################

import os, swat

# Set the SSL/TLS certificate:
os.environ["CAS_CLIENT_SSL_CA_LIST"] = '/path/to/ trustedcerts.pem'

# Connect to CAS:
s = swat.CAS("https://mpmprodvdmml.ondemand.sas.com/cas-shared-default-http/", 443)

# Print the server status to make sure we’re connected:
print(s.serverstatus())

# List all files in the caslib:
res = s.table.fileInfo(allFiles=True, caslib="Prostat_na_2006_149")
print(res)

# List all files in the dataFiles_859 subdirectory:
res = s.table.fileInfo(allFiles=True, caslib="Prostat_na_2006_149", path="dataFiles_859")
print(res)

# Create an output table to load the file into:
core_train = s.CASTable('core_train', replace=True, caslib='CASUSER')
s.table.loadTable(sourceCaslib="Prostat_na_2006_149", casOut=core_train, path="dataFiles_859/CoreTable_training.csv")

# View the first 5 rows:
print(core_train.head())

# Load the freqTab action set:
s.loadactionset('freqTab')

# Create a two-way cross tabulation table:
res = s.freqTab.freqTab(table=core_train, includeMissing=True, tabulate=[{'vars':{'DEATH', 'STUDYID'}}])
print(res)

# Save the CAS table to a .sashdat file in the CASUSER caslib:
core_train.table.save(caslib="CASUSER", name="core_train.sashdat", replace=True)
# Save the CAS table to a CSV file in the CASUSER caslib:
core_train.table.save(caslib="CASUSER", name="core_train.csv", replace=True)

# Drop the table from memory:
core_train.table.dropTable()