os.makedirs(outDir, exist_ok = True)


	# parse inputs and outputs
	inputInfos, outputInfos = parse_config(configFile)
	
	if varType == 'dis':
		inputData = extract_input_data(inputInfos)
	else:
		inputData = generate_input_data(inputInfos)
	
	
	# run simulation with Aspen
	try:
		aspenModel = Aspen(aspenFile)
		calculator = Excel(calculatorFile)

		simResults = simulate_using_aspen(aspenModel, calculator, inputData, outputInfos, outDir, nruns)
	
	finally:
		aspenModel.close()
		calculator.close()

	
	# save and plot results
	save_simulation_results(simResults, outDir)
	
	plot_hist(simResults, outputInfos[['Output', 'Unit']], outDir)
	
示例#2
0
def main():

    # Set the input and output files/directories
    aspenFile = os.path.abspath('DW1102A_AB.bkp')
    excelFile = os.path.abspath('DW1102A_2016UPDATES.xlsm')

    outDir = 'ethanol_output'
    os.makedirs(outDir, exist_ok=True)

    # ================================================================
    # Create Aspen Plus communicator
    # ================================================================
    print('Opening Aspen Plus model... ', end='')
    aspenModel = Aspen(aspenFile)
    print('Success!')

    # ================================================================
    # Write backup file with value updates/replacements
    # ================================================================
    # aspenPath: str, path in ASPEN tree
    # value: float or str, value to set
    # ifFortran: bool, whether it is a Fortran variable
    # ve_params['aspenPath'] = [value, ifFortran]
    ve_params = {}
    ve_params['path/in/aspen/tree'] = [0.75, False]
    ve_params['path/in/aspen/tree2'] = [0.01, False]

    DUMMY_OPERATION = True

    print('Changing values in model backup definition tree... ', end='')
    for key, value in ve_params.items():
        if not DUMMY_OPERATION:
            aspenModel.set_value(key, value[0], value[1])
        else:
            pass
    print('Success!')

    # ================================================================
    # Run the Aspen Plus model
    # ================================================================
    print('Running Aspen Plus model... ', end='')
    aspenModel.run_model()
    print('Success!')

    # ================================================================
    # Save current model state
    # ================================================================
    print('Saving current model definition... ', end='')
    tmpFile = '%s/%s.bkp' % (outDir, 'temp_backup')
    aspenModel.save_model(tmpFile)
    print('Success!')

    # ================================================================
    # Create Excel communicator and run calculator
    # ================================================================

    print('Opening Excel calculator... ', end='')
    excelCalculator = Excel(excelFile)
    print('Success!')

    print('Running Excel analysis... ', end='')
    if not DUMMY_OPERATION:
        excelCalculator.load_aspenModel(tmpFile)
        excelCalculator.run_macro('solvedcfror')
    print('Success!')

    # aspenModel.close()
    excelCalculator.close()
示例#3
0
def calculate_margin(inputInfos, outputInfos, aspenFiles, calculatorFiles,
                     marketPriceFiles, rinPriceFile, capital, credits):
    '''
	Parameters
	inputInfos: df, input infos for optimization, columns are ['Model', 'Input', 'Location', 'InputPath']
	outputInfos: df, output infos, columns are ['Model', 'Output', 'Unit', 'Location'] 
	aspenFiles: dict, keys are model names, values are aspen model path
	calculatorFiles: dict, keys are model names, values are calculator path
	marketPriceFiles: dict, keys are model names, values are market price file path
	rinPriceFile: str or None, rin price file, None if no subtractor rin price
	capital: str, whether to include the capital investment
	credits: str, whether to include the by-product credits in sugar model
	
	Returns
	margins: dict, keys are model names, values are df (index are time, columns are ['output (unit)', 'market price (unit)', 'margin (unit)'])
	totalMargins: df, index are time, columns are models
	'''

    margins = {}
    totalMargins = {}
    for model in inputInfos['Model'].unique():
        if model is np.nan: continue

        inputInfo = inputInfos[inputInfos['Model'] == model]
        inputInfo.index = range(inputInfo.shape[0])

        inputData = pd.DataFrame(index=inputInfo.index,
                                 columns=['Input', 'Location', 'Data'],
                                 dtype=object)
        for i, (input, location,
                inputPath) in inputInfo[['Input', 'Location',
                                         'InputPath']].iterrows():
            inputData.loc[i, :] = [
                input, location,
                pd.read_csv(inputPath, sep='\t',
                            index_col=0).values.reshape(-1)
            ]

        if capital == 'no':
            inputData.loc[inputData.shape[0], :] = [
                'Capital', 'DCFROR!B18',
                np.zeros(inputData.loc[0, 'Data'].size)
            ]

        if credits == 'no' and model == 'sugar':
            inputData.loc[inputData.shape[0], :] = [
                'Credits', 'OPEX!I48',
                np.zeros(inputData.loc[0, 'Data'].size)
            ]

        outputInfo = outputInfos.loc[outputInfos['Model'] == model,
                                     ['Output', 'Unit', 'Location']]
        outputInfo.index = [0]  # index start from 0
        output, unit = outputInfo.loc[0, :][['Output', 'Unit']]

        ###
        if output == 'MESP':
            outputInfo.loc[1, :] = ['Production', 'gal/yr', 'OPEX!B18']
        elif output == 'MSSP':
            outputInfo.loc[1, :] = ['Production', 'kg/yr', 'OPEX!B17']
        ###

        aspenFile = aspenFiles[model]
        calculatorFile = calculatorFiles[model]

        aspenModel = Aspen(aspenFile)
        calculator = Excel(calculatorFile)

        simResults = simulate_using_calculator(aspenModel, calculator,
                                               inputData, outputInfo)

        aspenModel.close()
        calculator.close()

        priceFile = marketPriceFiles[model]
        marketPrices = pd.read_csv(priceFile, sep='\t', index_col=0)

        data = pd.DataFrame(index=marketPrices.index)
        if rinPriceFile:
            rinPrice = pd.read_csv(rinPriceFile, sep='\t',
                                   index_col=0).values.reshape(-1)
            data['%s (%s)' %
                 (output, unit)] = simResults[output].values - rinPrice
        else:
            data['%s (%s)' % (output, unit)] = simResults[output].values
        data['market price (%s)' % unit] = marketPrices
        data['margin (%s)' %
             unit] = data['market price (%s)' % unit] - data['%s (%s)' %
                                                             (output, unit)]
        margins[model] = data

        ###
        totalMargin = data['margin (%s)' %
                           unit].values * simResults['Production'].values
        if output == 'MESP':
            totalMargin = totalMargin / 52
        elif output == 'MSSP':
            totalMargin = totalMargin / 52 * 2.2045
        totalMargins[model] = totalMargin

    totalMargins = pd.DataFrame(totalMargins, index=marketPrices.index)
    ###

    return margins, totalMargins