Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

psspy can't run with another case without any exception

I want to write a psse api, set every request as a object. When i try to get different .sav file's busdata, it will success. But it will break without any exception or error message, when i try to get branchdata after a get_buses request.

psse_python.py

import os
import sys
import exceptions
import settings

class ONCE_PSSE():
    def __init__(self, sav_path, function_name, arg_info=[]):
        self.sav_file = sav_path
        self.function_name = function_name
        self.arg_info = arg_info
        self.record_path = sav_path[:len(sav_path)-4]+"py"

    def work(self):
        settings.init_psse_path()
        import psspy
        perr = psspy.psseinit(0)
        try:
            perr = psspy.case(self.sav_file)
        except Exception as ex:
            return "Can't open the case :"+str(perr)
        ierr = psspy.startrecording(1, self.record_path)
        if self.function_name == "get_buses":
            buses_info = []
            ierr, iarray = psspy.abusint(-1, 2, ('NUMBER', 'TYPE',))
            cerr, carray = psspy.abuschar(-1, 2, ('NAME',))
            rerr, rarray = psspy.abusreal(-1, 2, ('BASE', 'PU'))

            if ierr != 0 :
                return {"abusint error": ierr}
            elif cerr != 0 :
                return {"abuschar error": cerr}
            elif rerr != 0 :
                return {"abusreal error": rerr}

            for i in range(0, len(iarray[0])):
                the_bus = {}
                the_bus["number"] = iarray[0][i]
                the_bus["code"] = iarray[1][i]
                the_bus["name"] = carray[0][i].decode('big5').strip()
                the_bus["base_kv"] = rarray[0][i]
                the_bus["pu"] = rarray[1][i]
                buses_info.append(the_bus)

            ierr = psspy.save(self.sav_file)        
            ierr = psspy.pssehalt_2()
            return buses_info
        elif self.function_name == "get_branches_data":
            branches_info = []
            ierr, iarray = psspy.abrnint(-1, 1, 1, 2, 1, ('FROMNUMBER', 'TONUMBER', 'STATUS', 'METERNUMBER',))
            cerr, carray = psspy.abrnchar(-1, 1, 1, 2, 1, ('ID', 'FROMNAME', 'TONAME',))

            if ierr != 0 :
                return {"abrnint error": ierr}
            elif cerr != 0 :
                return {"abrnchar error": cerr}

            for i in range(0, len(iarray[0])):
                the_branch = {}     
                the_branch["from_number"] = iarray[0][i]
                the_branch["id"] = carray[0][i].decode('big5').strip()
                the_branch["from_name"] = carray[1][i].decode('big5').strip()
                the_branch["to_number"] = iarray[1][i]
                the_branch["to_name"] = carray[2][i].decode('big5').strip()
                the_branch["in_service"] = (iarray[2][i] == 1)
                the_branch["metered"] = (iarray[3][i] == the_branch["from_number"])
                branches_info.append(the_branch)

            ierr = psspy.save(self.sav_file)
            ierr = psspy.pssehalt_2()
            return branches_info

    def __del__(self):
        print('__del__')

server.py

import logging       
from flask import Flask, jsonify, request, make_response, flash, redirect, url_for
import json
import os
import exceptions
from werkzeug.utils import secure_filename
import shutil
import uuid

#Flask
UPLOAD_FOLDER = "./psse_data/" #'/path/to/the/uploads'
ALLOWED_EXTENSIONS = {"sav"}
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

# check if the path exist
def check_dir_exist(the_dir):
    if os.path.isdir(the_dir):
        return True
    else:
        return False

# check if the file exist       
def check_file_exist(the_file):
    if os.path.isfile(the_file):
        return True
    else:
        return False

# check type of the upload file
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

#upload .sav
@app.route("/savs", methods=['POST'])
def upload_sav_file():
    # check if the post request has the file part
    if 'file' not in request.files:
        flash('No file part')
        return redirect(request.url)
    file = request.files['file']
    if file.filename == '':
        flash('No selected file')
        return redirect(request.url)
    if file and allowed_file(file.filename):
        sav_id = str(uuid.uuid4())
        worker_path = UPLOAD_FOLDER+sav_id+"/"
        os.mkdir(worker_path)
        # save .sav file
        filename = secure_filename(sav_id+'.sav')
        file.save(os.path.join(worker_path, filename))

        return jsonify({'sav_id':sav_id})

#sav Get buses data
@app.route("/savs/<string:sav_id>/buses", methods=['GET'])
def savs_get_buses(sav_id):
    import psse_functions
    sav_file = UPLOAD_FOLDER+sav_id+"/"+sav_id+".sav"
    if check_file_exist(sav_file):
        #buses_info = psse_functions.main_of_psspy(sav_file, "get_buses")
        tmp = psse_functions.ONCE_PSSE(sav_file, "get_buses")
        buses_info = tmp.work()
        tmp = None
        return jsonify(buses_info)
    else:
        return sav_id+".sav file not exists!"


#sav Get branches data
@app.route("/savs/<string:sav_id>/branches", methods=['GET'])
def savs_get_branches(sav_id):
    import psse_functions
    sav_file = UPLOAD_FOLDER+sav_id+"/"+sav_id+".sav"
    if check_file_exist(sav_file):
        #branches_info = psse_functions.main_of_psspy(sav_file, "get_branches_data")
        tmp = psse_functions.ONCE_PSSE(sav_file, "get_branches_data")
        branches_info = tmp.work()
        tmp = None
        return jsonify(branches_info)
    else:
        return sav_id+".sav file not exists!"

#delete sav
@app.route("/savs/<string:sav_id>", methods=['DELETE'])
def remove_sav_folder(sav_id):
    sav_path = UPLOAD_FOLDER+sav_id
    try:
        shutil.rmtree(sav_path)
    except OSError as e:
        return e

    if not check_dir_exist(sav_path):
        return "delete sav success."
    else:
        return "delete sav failed!"

if __name__ == '__main__':
    # Run Flask
    app.run('0.0.0.0', port = 5000)

psspy can't run with another case without any exception

  • I want to write a psse api, set every request as a object.
  • When i try to get different .sav file's busdata, .sav's bus_data, it will success. success.
  • But it program will break without any exception or error message, when i try to get branchdata after a get_buses request.

    get
    buses request (Vice versa).

psse_python.py

import os
import sys
import exceptions
import settings

class ONCE_PSSE():
    def __init__(self, sav_path, function_name, arg_info=[]):
        self.sav_file = sav_path
        self.function_name = function_name
        self.arg_info = arg_info
        self.record_path = sav_path[:len(sav_path)-4]+"py"

    def work(self):
        settings.init_psse_path()
        import psspy
        perr = psspy.psseinit(0)
        try:
            perr = psspy.case(self.sav_file)
        except Exception as ex:
            return "Can't open the case :"+str(perr)
        ierr = psspy.startrecording(1, self.record_path)
        if self.function_name == "get_buses":
            buses_info = []
            ierr, iarray = psspy.abusint(-1, 2, ('NUMBER', 'TYPE',))
            cerr, carray = psspy.abuschar(-1, 2, ('NAME',))
            rerr, rarray = psspy.abusreal(-1, 2, ('BASE', 'PU'))

            if ierr != 0 :
                return {"abusint error": ierr}
            elif cerr != 0 :
                return {"abuschar error": cerr}
            elif rerr != 0 :
                return {"abusreal error": rerr}

            for i in range(0, len(iarray[0])):
                the_bus = {}
                the_bus["number"] = iarray[0][i]
                the_bus["code"] = iarray[1][i]
                the_bus["name"] = carray[0][i].decode('big5').strip()
                the_bus["base_kv"] = rarray[0][i]
                the_bus["pu"] = rarray[1][i]
                buses_info.append(the_bus)

            ierr = psspy.save(self.sav_file)        
            ierr = psspy.pssehalt_2()
            return buses_info
        elif self.function_name == "get_branches_data":
            branches_info = []
            ierr, iarray = psspy.abrnint(-1, 1, 1, 2, 1, ('FROMNUMBER', 'TONUMBER', 'STATUS', 'METERNUMBER',))
            cerr, carray = psspy.abrnchar(-1, 1, 1, 2, 1, ('ID', 'FROMNAME', 'TONAME',))

            if ierr != 0 :
                return {"abrnint error": ierr}
            elif cerr != 0 :
                return {"abrnchar error": cerr}

            for i in range(0, len(iarray[0])):
                the_branch = {}     
                the_branch["from_number"] = iarray[0][i]
                the_branch["id"] = carray[0][i].decode('big5').strip()
                the_branch["from_name"] = carray[1][i].decode('big5').strip()
                the_branch["to_number"] = iarray[1][i]
                the_branch["to_name"] = carray[2][i].decode('big5').strip()
                the_branch["in_service"] = (iarray[2][i] == 1)
                the_branch["metered"] = (iarray[3][i] == the_branch["from_number"])
                branches_info.append(the_branch)

            ierr = psspy.save(self.sav_file)
            ierr = psspy.pssehalt_2()
            return branches_info

    def __del__(self):
        print('__del__')

server.py

import logging       
from flask import Flask, jsonify, request, make_response, flash, redirect, url_for
import json
import os
import exceptions
from werkzeug.utils import secure_filename
import shutil
import uuid

#Flask
UPLOAD_FOLDER = "./psse_data/" #'/path/to/the/uploads'
ALLOWED_EXTENSIONS = {"sav"}
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

# check if the path exist
def check_dir_exist(the_dir):
    if os.path.isdir(the_dir):
        return True
    else:
        return False

# check if the file exist       
def check_file_exist(the_file):
    if os.path.isfile(the_file):
        return True
    else:
        return False

# check type of the upload file
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

#upload .sav
@app.route("/savs", methods=['POST'])
def upload_sav_file():
    # check if the post request has the file part
    if 'file' not in request.files:
        flash('No file part')
        return redirect(request.url)
    file = request.files['file']
    if file.filename == '':
        flash('No selected file')
        return redirect(request.url)
    if file and allowed_file(file.filename):
        sav_id = str(uuid.uuid4())
        worker_path = UPLOAD_FOLDER+sav_id+"/"
        os.mkdir(worker_path)
        # save .sav file
        filename = secure_filename(sav_id+'.sav')
        file.save(os.path.join(worker_path, filename))

        return jsonify({'sav_id':sav_id})

#sav Get buses data
@app.route("/savs/<string:sav_id>/buses", methods=['GET'])
def savs_get_buses(sav_id):
    import psse_functions
    sav_file = UPLOAD_FOLDER+sav_id+"/"+sav_id+".sav"
    if check_file_exist(sav_file):
        #buses_info = psse_functions.main_of_psspy(sav_file, "get_buses")
        tmp = psse_functions.ONCE_PSSE(sav_file, "get_buses")
        buses_info = tmp.work()
        tmp = None
        return jsonify(buses_info)
    else:
        return sav_id+".sav file not exists!"


#sav Get branches data
@app.route("/savs/<string:sav_id>/branches", methods=['GET'])
def savs_get_branches(sav_id):
    import psse_functions
    sav_file = UPLOAD_FOLDER+sav_id+"/"+sav_id+".sav"
    if check_file_exist(sav_file):
        #branches_info = psse_functions.main_of_psspy(sav_file, "get_branches_data")
        tmp = psse_functions.ONCE_PSSE(sav_file, "get_branches_data")
        branches_info = tmp.work()
        tmp = None
        return jsonify(branches_info)
    else:
        return sav_id+".sav file not exists!"

#delete sav
@app.route("/savs/<string:sav_id>", methods=['DELETE'])
def remove_sav_folder(sav_id):
    sav_path = UPLOAD_FOLDER+sav_id
    try:
        shutil.rmtree(sav_path)
    except OSError as e:
        return e

    if not check_dir_exist(sav_path):
        return "delete sav success."
    else:
        return "delete sav failed!"

if __name__ == '__main__':
    # Run Flask
    app.run('0.0.0.0', port = 5000)