Example #1
0
    def SAS(self, line, cell):
        """
        %%SAS - send the code in the cell to a SAS Server

        This cell magic will execute the contents of the cell in a SAS
        session and return any generated output

        Example:
            %%SAS
            proc print data=sashelp.class;
            run;
            data a;
                set sashelp.cars;
            run;
        """
        
        mva = self.mva
        if len(line) and line in self.shell.user_ns:  # session supplied
            _mva = self.shell.user_ns[line]
            if isinstance(_mva, SASsession):
                mva = _mva
            else:
                return 'Invalid SAS Session object supplied'
        elif len(line) and not line in self.shell.user_ns:  # string supplied but not a session
            return 'Invalid SAS Session object supplied'
        else:  # no string should default to unnamed session
            try:
                if mva is None:
                    mva = SASsession()
                    self.mva = mva  # save the session for reuse
                else:
                    mva = self.mva
            except:
                return "this shouldn't happen"
        saveOpts="proc optsave out=__jupyterSASKernel__; run;"
        restoreOpts="proc optload data=__jupyterSASKernel__; run;"
        if len(line)>0:  # Save current SAS Options
            mva.submit(saveOpts)

        if line.lower()=='smalllog':
            mva.submit("options nosource nonotes;")

        elif line is not None and line.startswith('option'):
            mva.submit(line + ';')

        res = mva.submit(cell)
        dis = self._which_display(res['LOG'], res['LST'])

        if len(line)>0:  # Restore SAS options 
            mva.submit(restoreOpts)

        return dis
# load objects needed from packages in the standard library
from datetime import datetime
from pathlib import Path

# load third-party SASPy package, and create a connection to a SAS kernel
from saspy import SASsession
sas = SASsession()

# define data-analysis SAS file to be executed
SAS_INPUT_FILE = 'STAT697-01_s20-team-1_data_analysis_by_BB.sas'

# get value of automatic macro variable &SYSJOBID corresponding to the SAS session
sas_job_id = sas.symget("SYSJOBID")

# if needed, created directory ./sas_output, where all output will be written
sas_output_directory_name = 'sas_output'
sas_output_directory = Path(sas_output_directory_name)
sas_output_directory.mkdir(parents=True, exist_ok=True)

# set parameters for outputing time-stamped log and results files
current_timestamp = datetime.now().strftime("%Y-%m-%dT%H-%M-%S")
sas_output_filename_stem = '%s-job_id_%s' % (current_timestamp, sas_job_id)
sas_log_file = './%s/%s.log' % (sas_output_directory_name,
                                sas_output_filename_stem)
sas_results_file = './%s/%s.html' % (sas_output_directory_name,
                                     sas_output_filename_stem)

# read contents of data-analysis SAS file, and submit to SAS session
with open(SAS_INPUT_FILE) as fp:
    sas_submit_return_value = sas.submit(fp.read(), results='')
    print_with_title(type(hello_world_dict), 'The type of hello_world_dict:')

    # Example 5. Create a DataFrame from a dictionary of lists, and print its value and type
    hello_world_df = DataFrame(
        {
            'salutation': ['Hello', 'DataFrame'],
            'valediction': ['Goodbye', 'dict'],
            'part of speech': ['exclamation', 'noun'],
        }
    )
    print_with_title(hello_world_df, 'The value of hello_world_df:')
    print_with_title(hello_world_df.shape, 'The shape of hello_world_df:')
    print_with_title(hello_world_df.info(), 'Information about hello_world_df:')

    # Example 6. Create a SAS session object and print its type
    sas = SASsession()
    print_with_title(type(sas), 'The type of SAS session object sas:')

    # Example 7. Compute the Python equivalent of the following SAS code after loading sashelp.fish into a DataFrame:
    # PROC MEANS DATA=sashelp.fish;
    # RUN;
    # PROC PRINT DATA=sashelp.fish(obs=5);
    # RUN;
    fish_df = sas.sasdata2dataframe(table='fish', libref='sashelp')
    print_with_title(fish_df, 'The value of fish_df:')
    print_with_title(fish_df.describe(), 'The Python equivalent of PROC MEANS using fish_df:')
    print_with_title(fish_df.head(), 'The first five rows of fish_df:')

    # Example 8. Compute and print a DataFrame containing the Python equivalent of the following SAS code:
    # PROC MEANS STD MEAN MIN MAX DATA=sashelp.fish;
    #     CLASS Species;
# Everything is better with friends: Executing SAS® code in Python scripts with
# SASPy, and turbocharging your SAS programming with open-source tooling
#
# Half-day class, Western Users of SAS Software (WUSS) 2019

###############################################################################
# Exercise 13: Imitating the SAS macro processor                              #
###############################################################################

# Lines 12-14 load modules needed for exercises and should be left as-is
from class_setup import print_with_title
from saspy import SASsession
sas = SASsession()

###############################################################################
#                                                                             #
# Exercise 13. [Python w/ saspy] Imitate the SAS Macro Processor              #
#                                                                             #
# Instructions: Uncomment the code immediately below, and then execute        #
#                                                                             #
###############################################################################

# sas_code_fragment = 'proc means data=sashelp.%s; run;'
# for dsn in ['fish', 'iris']:
#     sas_submit_return_value = sas.submit(
#         sas_code_fragment % dsn,
#         results='TEXT'
#     )
#     print_with_title(
#         sas_submit_return_value['LST'],
#         'SAS results from PROC MEANS applies to sashelp.%s:' % dsn
Example #5
0
# Everything is better with friends: Executing SAS® code in Python scripts with
# SASPy, and turbocharging your SAS programming with open-source tooling
#
# Half-day class, Western Users of SAS Software (WUSS) 2019

###############################################################################
# Exercise 10: Getting SASPy Environment Info                                 #
###############################################################################

# Lines 12-14 load modules needed for exercises and should be left as-is
from class_setup import print_with_title
from saspy import SASsession
sas = SASsession()

###############################################################################
#                                                                             #
# Exercise 10. [Python w/ saspy] Get info about a SAS session                 #
#                                                                             #
# Instructions: Uncomment the code immediately below, and then execute        #
#                                                                             #
###############################################################################

# Orginal Version
sas_submit_return_value = sas.submit('PROC PRODUCT_STATUS; RUN;')
sas_submit_log = sas_submit_return_value['LOG']
print_with_title(sas_submit_log, 'SAS log from PROC PRODUCT_STATUS:')

# Verify the output from PROC PRODUCT_STATUS is empty
print('The output from PROC PRODUCT_STATUS appears below.')
print(sas.submit('PROC PRODUCT_STATUS; RUN;')['LST'])
print('The output from PROC PRODUCT_STATUS appears above.')
Example #6
0
# Everything is better with friends: Executing SAS® code in Python scripts with
# SASPy, and turbocharging your SAS programming with open-source tooling
#
# Half-day class, Western Users of SAS Software (WUSS) 2019

###############################################################################
# Exercise 13: Imitating the SAS macro processor                              #
###############################################################################

# Lines 12-14 load modules needed for exercises and should be left as-is
from class_setup import print_with_title
from saspy import SASsession
sas = SASsession()

###############################################################################
#                                                                             #
# Exercise 13. [Python w/ saspy] Imitate the SAS Macro Processor              #
#                                                                             #
# Instructions: Uncomment the code immediately below, and then execute        #
#                                                                             #
###############################################################################

# Original Version
sas_code_fragment = 'proc means data=sashelp.%s; run;'
for dsn in ['fish', 'iris']:
    sas_submit_return_value = sas.submit(sas_code_fragment % dsn,
                                         results='TEXT')
    print_with_title(
        sas_submit_return_value['LST'],
        'SAS results from PROC MEANS applies to sashelp.%s:' % dsn)
Example #7
0
# Everything is better with friends: Executing SAS® code in Python scripts with
# SASPy, and turbocharging your SAS programming with open-source tooling
#
# Half-day class, Western Users of SAS Software (WUSS) 2019

###############################################################################
# Exercises 11-12: SASPy Convenience Methods                                  #
###############################################################################

# Lines 12-14 load modules needed for exercises and should be left as-is
from class_setup import print_with_title
from saspy import SASsession
sas = SASsession()

###############################################################################
#                                                                             #
# Exercise 11. [Python w/ saspy] Connect directly to a SAS dataset            #
#                                                                             #
# Instructions: Uncomment the code immediately below, and then execute        #
#                                                                             #
###############################################################################

fish_sds = sas.sasdata(table='fish', libref='sashelp')
print_with_title(type(fish_sds), 'The type of fish_sds:')
print_with_title(fish_sds.columnInfo(),
                 'The Python equivalent of PROC CONTENTS:')
print_with_title(fish_sds.means(), 'The Python equivalent of PROC MEANS:')

# Notes:
# 1. The SASdata object fish_sds (meaning a direct connection to the disk-based
#    SAS dataset sashelp.fish, not an in-memory DataFrame) is created, and the
Example #8
0
# Everything is better with friends: Executing SAS® code in Python scripts with
# SASPy, and turbocharging your SAS programming with open-source tooling
#
# Half-day class, Western Users of SAS Software (WUSS) 2019

###############################################################################
# Exercises 14-17: Common DataFrame Operations                                #
###############################################################################

# Lines 12-14 load modules needed for exercises and should be left as-is
from class_setup import print_with_title
from saspy import SASsession
sas = SASsession()

###############################################################################
#                                                                             #
# Exercise 14. [Python w/ saspy] Adding and dropping columns                  #
#                                                                             #
# Instructions: Uncomment the code immediately below, and then execute        #
#                                                                             #
###############################################################################

# Original Version
class_df = sas.sasdata2dataframe(table='class', libref='sashelp')
print_with_title(class_df.head(), 'The first 5 rows of class_df:')

class_df['BMI'] = (class_df['Weight'] / class_df['Height']**2) * 703
print_with_title(
    class_df.head(),
    'The first 5 rows of class_df after a new column has been added:')