Beispiel #1
0
def test2018(pathList):
    # 读取公共配置(职位、职位权重之类)
    with open("../file/Common configuration/totalGradeCrewConfig.json"
              ) as json_model1:
        configModel = json.load(json_model1)

    finalResult = []
    for filePath in pathList:
        # print(filePath)
        # 读取船员、船舶和船管公司信息
        with open(filePath, encoding='utf-8') as json_model2:
            model = json.load(json_model2)
        keys = set(model.keys())
        # 连接数据库
        conn = pymysql.connect(host="10.18.34.221",
                               user="******",
                               password="******",
                               database="risk",
                               charset="utf8")
        cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)  # 返回字典数据类型

        # 船公司分数
        if "companyName" in keys:
            companyName = model["companyName"]
            sql = "select GRADE from management_company where COMPANY = " + "'" + companyName + "'"
            cursor.execute(sql)
            result = cursor.fetchone()
            if result:
                companyGrade = result["GRADE"]
            else:
                companyGrade = 100
        else:
            companyGrade = 100
        # print("companyGrade: ", companyGrade)

        # 船舶分数
        if "vesselName" in keys:
            vesselName = model["vesselName"]
            sql1 = "select SHIP_GRADE from ship_totalgrade where VESSEL_NAME = " + "'" + vesselName + "'"
            cursor.execute(sql1)
            result = cursor.fetchone()
            if result:
                vesselGrade = result["SHIP_GRADE"]
            else:
                vesselGrade = 85
        else:
            vesselGrade = 85
        # print("vesselGrade: ", vesselGrade)

        # 船员分数
        position = {
            "captain": 0,
            "chief engineer": 1,
            "political commissar": 2,
            "mate captain": 3,
            "senior seaman": 4,
            "ordinary seaman": 5,
            "intern senior seaman": 6,
            "intern ordinary seaman": 7
        }
        delList = []
        existPosition = []
        positionGrade = dict()
        for k, v in position.items():
            if k in keys:
                existPosition.append(k)
                GradeSum = 0
                for i in model[k]:
                    sql = "select HISTORY_TOTAL_GRADE from emp_history_totalgrade where EMP_NAME = " + "'" + i + "'"
                    cursor.execute(sql)
                    result = cursor.fetchone()
                    if result:
                        GradeSum += result["HISTORY_TOTAL_GRADE"]
                    else:
                        GradeSum += 85
                positionGrade[k] = GradeSum / len(model[k])
            else:
                delList.append(v)

        # print(positionGrade)
        matrix = np.array(configModel["positionWeight"], dtype=float)
        positionWeight = np.delete(np.delete(matrix, delList, axis=1),
                                   delList,
                                   axis=0)
        weight = dict()
        for i, j in zip(existPosition, calculateWeight(positionWeight)):
            weight[i] = j
        # print(weight)
        personGrade = 0
        for k, v in positionGrade.items():
            personGrade += v * weight[k]
        # print("personGrade :", personGrade)

        # 综合三大因素得分,船员40%,船舶占比30%,船管公司占比30%
        grade = round(
            float(vesselGrade) * 0.35 + float(companyGrade) * 0.3 +
            float(personGrade) * 0.35, 0)
        finalResult.append(grade)

    return finalResult
Beispiel #2
0
def accidentRecord():
    account = "csbc/[email protected]:1521/cbgl"
    conn1 = cx_Oracle.connect(account)
    conn2 = pymysql.connect(host="10.18.34.221",
                            user="******",
                            password="******",
                            database="risk",
                            charset="utf8")
    cursor2 = conn2.cursor(cursor=pymysql.cursors.DictCursor)  # 返回字典数据类型
    cursor1 = conn1.cursor()

    # 读取公共配置(职位、职位权重之类)
    with open("../file/Common configuration/totalGradeCrewConfig.json"
              ) as json_model1:
        configModel = json.load(json_model1)

    myFile = open('accidentResult' + '.csv', 'a+')
    # 第一项是船员集合综合分,第二项是船舶分,第三项是船管公司分
    myWriter = csv.writer(myFile)

    # 去事故表里查航次
    sql1 = "select COMPANY, VESSEL_CODE, ACCIDENT_TIME, ACCIDENT_LEVEL from SSM_VESSEL_ACCIDENT_REPORT"
    cursor1.execute(sql1)
    result1 = cursor1.fetchall()
    for r in result1:
        companyGrade = 95
        vesselGrade = 85
        accidentLevel = "F"
        if r[0]:
            companyCode = r[0]
            sql2 = "SELECT OFFICE_NAME FROM VW_SYS_ORGANIZATION_INFO where OFFICE_CODE = '" + companyCode + "'"
            cursor1.execute(sql2)
            result2 = cursor1.fetchone()
            if result2:
                company = result2[0]
                sql3 = "select GRADE from management_company_copy1 where COMPANY = '" + company + "'"
                cursor2.execute(sql3)
                result3 = cursor2.fetchone()
                if result3:
                    companyGrade = result3["GRADE"]

        if r[1]:
            vesselCode = r[1]
            sql4 = "select SHIP_GRADE from ship_totalgrade where VESSEL_CODE = '" + vesselCode + "'"
            cursor2.execute(sql4)
            result4 = cursor2.fetchone()
            if result4:
                vesselGrade = result4["SHIP_GRADE"]

        if r[2] and r[1]:
            accidentTime = r[2].strftime("%Y-%m-%d")
            sql5 = "select EMP_NAME, POSI_CODE from VW_CDM_EMP_INFO where vessel_code = '" + vesselCode + "' and UP_SHIP <= to_date( '" + accidentTime + "', 'yyyy-MM-dd HH24:MI:SS') and (DOWN_SHIP >= to_date( '" + accidentTime + "', 'yyyy-MM-dd HH24:MI:SS') or DOWN_SHIP is null)"
            cursor1.execute(sql5)
            result5 = cursor1.fetchall()
            # print(result5)
            if result5:
                emp_posi = dict()
                for x in result5:

                    # print(x[0])

                    if x[1]:
                        sql6 = "select SM_POS_TYPE from smm_ass_position where POSITION_CODE = '" + x[
                            1] + "'"
                        cursor2.execute(sql6)
                        result6 = cursor2.fetchone()
                        if result6:
                            emp_posi[x[0]] = result6["SM_POS_TYPE"]
                # print(emp_posi)

                posi_grade = dict()
                count = [0, 0, 0, 0, 0, 0, 0, 0]
                for emp, posi in emp_posi.items():
                    if posi == "1":
                        count[0] = count[0] + 1
                    if posi == "2":
                        count[1] = count[1] + 1
                    if posi == "3":
                        count[2] = count[2] + 1
                    if posi == "4":
                        count[3] = count[3] + 1
                    if posi == "5":
                        count[4] = count[4] + 1
                    if posi == "6":
                        count[5] = count[5] + 1
                    if posi == "7":
                        count[6] = count[6] + 1
                    if posi == "8":
                        count[7] = count[7] + 1
                    sql7 = "select HISTORY_TOTAL_GRADE from emp_history_totalgrade where EMP_NAME = '" + emp + "'"
                    cursor2.execute(sql7)
                    result7 = cursor2.fetchone()
                    if result7:
                        personGrade = result7["HISTORY_TOTAL_GRADE"]
                    else:
                        personGrade = 85
                    if posi in posi_grade:
                        posi_grade[posi] = posi_grade[posi] + personGrade
                    else:
                        posi_grade[posi] = personGrade
                # print(posi_grade)
                # while 0 in count:
                #     count.remove(0)
                # print(count)
                posi_Avegrade = dict()
                for posi, grade in posi_grade.items():
                    posi_Avegrade[posi] = posi_grade[posi] / count[int(posi) -
                                                                   1]
                # print(posi_Avegrade)
                aveGrade = []
                if "1" in posi_Avegrade:
                    aveGrade.append(posi_Avegrade["1"])
                if "2" in posi_Avegrade:
                    aveGrade.append(posi_Avegrade["2"])
                if "3" in posi_Avegrade:
                    aveGrade.append(posi_Avegrade["3"])
                if "4" in posi_Avegrade:
                    aveGrade.append(posi_Avegrade["4"])
                if "5" in posi_Avegrade:
                    aveGrade.append(posi_Avegrade["5"])
                if "6" in posi_Avegrade:
                    aveGrade.append(posi_Avegrade["6"])
                if "7" in posi_Avegrade:
                    aveGrade.append(posi_Avegrade["7"])
                if "8" in posi_Avegrade:
                    aveGrade.append(posi_Avegrade["8"])
                # print(aveGrade)

                delSet = {0, 1, 2, 3, 4, 5, 6, 7} - set(
                    int(x) - 1 for x in posi_Avegrade.keys())
                positionWeight = np.array(configModel["positionWeight"],
                                          dtype=float)
                positionWeight = np.delete(np.delete(positionWeight,
                                                     list(delSet),
                                                     axis=1),
                                           list(delSet),
                                           axis=0)
                positionWeight_T = np.mat(calculateWeight(positionWeight)).T
                # print(positionWeight_T)
                empGrade = (np.mat(aveGrade) * positionWeight_T)[0, 0]
                if empGrade == 0:
                    continue
        if r[3]:
            accidentLevel = r[3]
        # print(companyGrade)
        # print(vesselGrade)
        # print(empGrade)
        # print(accidentLevel)

        myWriter.writerow([empGrade, vesselGrade, companyGrade, accidentLevel])
    myFile.close()
def evaluateTotalGrade(jsonPath):
    # 读取公共配置(职位、职位权重之类)
    with open("../file/Common configuration/evaluateCrewConfig.json"
              ) as json_model1:
        configModel = json.load(json_model1)

    # 读取某个时期的详细打分情况
    with open(jsonPath) as json_model2:
        model = json.load(json_model2)

    # 检验一下比较矩阵是否合理
    testConsistency(np.array(configModel["regularEmployeeWeight"],
                             dtype=float))
    # testConsistency(np.array(model["internWeight"], dtype=float))
    testConsistency(np.array(configModel["ItemWeight"], dtype=float))

    # 根据比较矩阵算各项权重
    # 职位权重,由于可能有职位空缺,所以首先要在矩阵中剔除不存在职位
    # 正式船员矩阵
    matrix1 = np.array(configModel["regularEmployeeWeight"], dtype=float)
    zeroList1 = []
    for i in range(6):
        if model["quantity"][i] == 0:
            zeroList1.append(i)
    matrix1 = np.delete(np.delete(matrix1, zeroList1, axis=1),
                        zeroList1,
                        axis=0)
    regularEmployeeWeight = calculateWeight(matrix1)
    # print(regularEmployeeWeight)
    # 将它矩阵化并转置
    regularEmployeeWeight_T = np.mat(regularEmployeeWeight).T

    # 实习船员矩阵在计算实习船员分数时再进行计算

    # 评价指标的权重
    matrix3 = np.array(configModel["ItemWeight"], dtype=float)
    if model["quantity"][-1] == 0 and model["quantity"][-2] == 0:
        matrix3 = np.delete(np.delete(matrix3, [3, 4], axis=1), [3, 4], axis=0)
        ItemWeight = calculateWeight(matrix3)
        # 将它矩阵化并转置
        ItemWeight_T = np.mat(ItemWeight).T
    else:
        ItemWeight = calculateWeight(matrix3)
        # 将它矩阵化并转置
        ItemWeight_T = np.mat(ItemWeight).T

    # print("ItemWeight_T = ", ItemWeight_T)

    # 有多少职位
    num1 = len(configModel["employee"])

    employeeTotalGrade = []
    for employeeItemGrade in configModel["employeeItemGrade"]:
        employee_grade = []
        for i in range(num1):
            employee = configModel["employee"][i]
            quantity = model["quantity"][i]
            totalGrade = 0
            if quantity != 0:
                for j in range(quantity):
                    if employee in model[employeeItemGrade]:
                        totalGrade += sum(
                            model[employeeItemGrade][employee][j])
                averageGrade = totalGrade / quantity
                employee_grade.append(averageGrade)
        # 将五项评价的分数存放于同一个列表
        employeeTotalGrade.append(employee_grade)
    # print("employeeTotalGrade = ", employeeTotalGrade)

    # 根据职位权重折算得到新的五项指标的分数
    # 先计算正式员工的折算分
    regularEmployee = np.array(regularEmployeeWeight).shape[0]
    regularEmployeeTotalGrade = []
    for i in range(0, configModel["howMuchRegularEmployeeItemGrade"]):
        matrix = np.mat(
            employeeTotalGrade[i][:regularEmployee]) * regularEmployeeWeight_T
        value = matrix[0, 0]
        regularEmployeeTotalGrade.append(value)
    # print("regularEmployeeTotalGrade =", regularEmployeeTotalGrade)

    # 先讨论是否存在实习船员再计算实习员工的折算分
    internEmployeeTotalGrade = []
    if not (model["quantity"][-1] == 0 and model["quantity"][-2] == 0):
        matrix2 = np.array(configModel["internWeight"], dtype=float)
        zeroList2 = []
        for i in range(6, 8):
            if model["quantity"][i] == 0:
                zeroList2.append(i - 6)
        matrix2 = np.delete(np.delete(matrix2, zeroList2, axis=1),
                            zeroList2,
                            axis=0)
        internWeight = calculateWeight(matrix2)
        # 将它矩阵化并转置
        internWeight_T = np.mat(internWeight).T

        # print("internWeight_T =", internWeight_T)

        internEmployee = np.array(internWeight).shape[0]
        internEmployeeTotalGrade = []
        for i in range(-configModel["howMuchInternItemGrade"], 0):
            matrix = np.mat(
                employeeTotalGrade[i][-internEmployee:]) * internWeight_T
            value = matrix[0, 0]
            internEmployeeTotalGrade.append(value)
    # print("internEmployeeTotalGrade =", internEmployeeTotalGrade)

    # 将正式员工成绩列表和实习员工成绩列表整合
    regularEmployeeTotalGrade.extend(internEmployeeTotalGrade)
    # print("regularEmployeeTotalGrade =", regularEmployeeTotalGrade)
    # 最终得分
    finalGrade = (np.mat(regularEmployeeTotalGrade) * ItemWeight_T)[0, 0]
    return finalGrade
Beispiel #4
0
def Voyage(vesselCode, flag):
    account = "csbc/[email protected]:1521/cbgl"
    conn1 = cx_Oracle.connect(account)
    cursor1 = conn1.cursor()

    conn2 = pymysql.connect(host="10.18.34.221", user="******", password="******", database="risk", charset="utf8")
    cursor2 = conn2.cursor(cursor=pymysql.cursors.DictCursor)  # 返回字典数据类型

    # 读取公共配置(职位、职位权重之类)
    with open("../file/Common configuration/totalGradeCrewConfig.json") as json_model1:
        configModel = json.load(json_model1)

    myFile = open('result' + flag + '.csv', 'a+')
    # 第一项是船员集合综合分,第二项是船舶分,第三项是船管公司分
    myWriter = csv.writer(myFile)

    # 首先去事故表查出事船舶+航次
    sql9 = "select VESSEL_CODE, VOYAGE, ACCIDENT_LEVEL from SSM_VESSEL_ACCIDENT_REPORT"
    cursor1.execute(sql9)
    result9 = cursor1.fetchall()
    vesselVoyage = dict()
    for r in result9:
        if r[0] and r[1] and r[2]:
            vesselVoyage[r[0]] = [r[1], r[2]]
    # print(vesselVoyage)
    # 出事船舶名单
    accident = vesselVoyage.keys()

    # 去航次表里查航次
    # sql1 = "select VESSEL_CODE from VOC_VOYAGE_TASK"
    # cursor1.execute(sql1)
    # result1 = cursor1.fetchall()
    # vesselCode = set()
    # for i in result1:
    #     vesselCode.add(i[0])
    # vessel_code 集合
    # print(vesselCode)
    # vesselCode = {'B337'}
    for code in vesselCode:

        print(code)

        sql6 = "select SHIP_GRADE from ship_totalgrade WHERE VESSEL_CODE = '" + code + "'"
        cursor2.execute(sql6)
        result6 = cursor2.fetchone()
        if result6:
            vesselGrade = result6["SHIP_GRADE"]
        else:
            vesselGrade = 87

        sql7 = "select SAFE_MANAGER, BUSI_MAINBODY, MANAGER from vw_vop_vessel_manage_bk1 WHERE VESSEL_CODE = '" + code + "'"
        cursor2.execute(sql7)
        result7 = cursor2.fetchone()
        if result7:
            if result7["SAFE_MANAGER"]:
                company = result7["SAFE_MANAGER"]
            elif result7["BUSI_MAINBODY"]:
                company = result7["BUSI_MAINBODY"]
            else:
                company = result7["MANAGER"]
            if company:
                sql8 = "select GRADE from management_company_copy1 where COMPANY = '" + company + "'"
                cursor2.execute(sql8)
                result8 = cursor2.fetchone()
                if result8:
                    if result8["GRADE"]:
                        companyGrade = result8["GRADE"]
            else:
                continue

        sql2 = "select BEGIN_TIME, VOYAGE_NO from VOC_VOYAGE_TASK WHERE VESSEL_CODE = '" + code + "'"
        cursor1.execute(sql2)
        result2 = cursor1.fetchall()

        time = []
        for i in result2:
            if i[0] and i[1]:
                time.append([i[0].strftime("%Y-%m-%d"), i[1]])
        # print(time)
        # time = ["2019-03-16 16:50:00"]
        # 事故等级O表示没出事,ABCDE依次增加严重度,F待定

        for t in time:
            level = "O"
            # 确定该航次是不是出事船舶
            if (code in accident) and (t[1] == vesselVoyage[code][0]):
                # 事故等级
                level = vesselVoyage[code][1]

            print(t[0])

            sql3 = "select EMP_NAME, POSI_CODE from VW_CDM_EMP_INFO where vessel_code = '" + code + "' and UP_SHIP <= to_date( '" + t[0] + "', 'yyyy-MM-dd HH24:MI:SS') and (DOWN_SHIP >= to_date( '" + t[0] + "', 'yyyy-MM-dd HH24:MI:SS') or DOWN_SHIP is null)"
            cursor1.execute(sql3)
            result3 = cursor1.fetchall()
            # print(result3)

            emp_posi = dict()
            for r in result3:

                print(r[0])

                if r[1]:
                    sql4 = "select SM_POS_TYPE from smm_ass_position where POSITION_CODE = '" + r[1] + "'"
                    cursor2.execute(sql4)
                    result4 = cursor2.fetchone()
                    if result4:
                        emp_posi[r[0]] = result4["SM_POS_TYPE"]
            # print(emp_posi)

            posi_grade = dict()
            count = [0, 0, 0, 0, 0, 0, 0, 0]
            for emp, posi in emp_posi.items():
                if posi == "1":
                    count[0] = count[0] + 1
                if posi == "2":
                    count[1] = count[1] + 1
                if posi == "3":
                    count[2] = count[2] + 1
                if posi == "4":
                    count[3] = count[3] + 1
                if posi == "5":
                    count[4] = count[4] + 1
                if posi == "6":
                    count[5] = count[5] + 1
                if posi == "7":
                    count[6] = count[6] + 1
                if posi == "8":
                    count[7] = count[7] + 1
                sql5 = "select HISTORY_TOTAL_GRADE from emp_history_totalgrade where EMP_NAME = '" + emp + "'"
                cursor2.execute(sql5)
                result5 = cursor2.fetchone()
                if result5:
                    personGrade = result5["HISTORY_TOTAL_GRADE"]
                else:
                    personGrade = 85
                if posi in posi_grade:
                    posi_grade[posi] = posi_grade[posi] + personGrade
                else:
                    posi_grade[posi] = personGrade
            # print(posi_grade)
            # while 0 in count:
            #     count.remove(0)
            # print(count)
            posi_Avegrade = dict()
            for posi, grade in posi_grade.items():
                posi_Avegrade[posi] = posi_grade[posi] / count[int(posi) - 1]
            # print(posi_Avegrade)
            aveGrade = []
            if "1" in posi_Avegrade:
                aveGrade.append(posi_Avegrade["1"])
            if "2" in posi_Avegrade:
                aveGrade.append(posi_Avegrade["2"])
            if "3" in posi_Avegrade:
                aveGrade.append(posi_Avegrade["3"])
            if "4" in posi_Avegrade:
                aveGrade.append(posi_Avegrade["4"])
            if "5" in posi_Avegrade:
                aveGrade.append(posi_Avegrade["5"])
            if "6" in posi_Avegrade:
                aveGrade.append(posi_Avegrade["6"])
            if "7" in posi_Avegrade:
                aveGrade.append(posi_Avegrade["7"])
            if "8" in posi_Avegrade:
                aveGrade.append(posi_Avegrade["8"])
            # print(aveGrade)

            delSet = {0, 1, 2, 3, 4, 5, 6, 7} - set(int(x) - 1 for x in posi_Avegrade.keys())
            positionWeight = np.array(configModel["positionWeight"], dtype=float)
            positionWeight = np.delete(np.delete(positionWeight, list(delSet), axis=1), list(delSet), axis=0)
            positionWeight_T = np.mat(calculateWeight(positionWeight)).T
            # print(positionWeight_T)
            empGrade = (np.mat(aveGrade) * positionWeight_T)[0, 0]
            # print(empGrade)
            if empGrade == 0:
                continue
            # print(vesselGrade)
            # print(companyGrade)

            myWriter.writerow([empGrade, vesselGrade, companyGrade, level])
    myFile.close()
Beispiel #5
0
def PersonGradeTest(start, end, fileList):
    # 读取公共配置(职位、职位权重之类)
    with open("../../file/Common configuration/totalGradeCrewConfig.json"
              ) as json_model1:
        configModel = json.load(json_model1)
    # 单测用
    # with open("../file/Common configuration/totalGradeCrewConfig.json") as json_model1:
    #     configModel = json.load(json_model1)

    conn = pymysql.connect(host="127.0.0.1",
                           user="******",
                           password="******",
                           database="risk",
                           charset="utf8")
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)  # 返回字典数据类型

    for personPath in fileList[start:end]:
        print(personPath)
        # 读取船员个人成绩
        with open(personPath) as json_model2:
            model = json.load(json_model2)

        # 检验职位比较矩阵是否合理
        # testConsistency(np.array(configModel["positionWeight"], dtype=float))

        # 如果该船员不存在历史记录默认其历史分为85
        if not model["positionTimeGrade"]:
            totalGrade = 85
        else:
            '''
            测试用,仅保留2018年以前的记录
            '''
            # 按时间从远到近排序,times列表
            Alltimes = sorted(model["positionTimeGrade"], reverse=True)
            # print(Alltimes)
            times = []
            for i in Alltimes:
                y = i.split("-")[0]
                if int(y) < 2018:
                    times.append(i)
            # print(times)

            if times:
                howManyYearsAgo = []
                for time in times:
                    time = time.split("-")
                    # 实际用当前年份
                    howManyYearsAgo.append(datetime.datetime.now().year -
                                           int(time[0]))
                # print(howManyYearsAgo)

                # 和今年差0年一档,差1年一档,差2、3年一档,差4、5年一档,差6、7、8、9、10年一档,差10年以上一档
                timeWeight = np.array(configModel["timeWeight"], dtype=float)
                delSet = set()
                if 0 not in howManyYearsAgo:
                    delSet.add(0)
                if 1 not in howManyYearsAgo:
                    delSet.add(1)
                if 2 not in howManyYearsAgo and 3 not in howManyYearsAgo:
                    delSet.add(2)
                if 4 not in howManyYearsAgo and 5 not in howManyYearsAgo:
                    delSet.add(3)
                if 6 not in howManyYearsAgo and 7 not in howManyYearsAgo and 8 not in howManyYearsAgo and 9 not in howManyYearsAgo and 10 not in howManyYearsAgo:
                    delSet.add(4)
                if max(howManyYearsAgo) <= 10:
                    delSet.add(5)

                timeWeight = np.delete(np.delete(timeWeight,
                                                 list(delSet),
                                                 axis=1),
                                       list(delSet),
                                       axis=0)
                # print(timeWeight)
                # 根据timeWeight计算权重
                timeWeightList_T = np.mat(calculateWeight(timeWeight)).T
                # print(timeWeightList_T)

                # 找到存在的历史成绩档次的位置
                haveValueSet = {0, 1, 2, 3, 4, 5} - delSet
                # print(haveValueSet)

                moreTen = []
                sixToTenYears = []
                fourToFive = []
                twoTOThree = []
                one = []
                zero = []
                total = []
                for year in howManyYearsAgo:
                    if year > 10:
                        moreTen.append(year)
                    if 6 <= year <= 10:
                        sixToTenYears.append(year)
                    if 4 <= year <= 5:
                        fourToFive.append(year)
                    if 2 <= year <= 3:
                        twoTOThree.append(year)
                    if year == 1:
                        one.append(year)
                    if year == 0:
                        zero.append(year)
                total.append(zero)
                total.append(one)
                total.append(twoTOThree)
                total.append(fourToFive)
                total.append(sixToTenYears)
                total.append(moreTen)
                # print(total)

                # 将存储年份差的列表变成对应年份的职位和分数
                flag = 0
                for i in haveValueSet:
                    for j in range(len(total[i])):
                        total[i][j] = model["positionTimeGrade"][times[flag]]
                        flag += 1
                # print(total)

                list1 = []
                for i in haveValueSet:
                    captainGrade = []
                    chiefEngineerGrade = []
                    politicalCommissarGrade = []
                    mateCaptainGrade = []
                    seniorSeamanGrade = []
                    ordinarySeamanGrade = []
                    internSeniorGrade = []
                    internOrdinaryGrade = []
                    list2 = []
                    for j in total[i]:
                        if list(j.keys())[0] == "captain":
                            captainGrade.append(j.get("captain"))
                        if list(j.keys())[0] == "chief engineer":
                            chiefEngineerGrade.append(j.get("chief engineer"))
                        if list(j.keys())[0] == "political commissar":
                            politicalCommissarGrade.append(
                                j.get("political commissar"))
                        if list(j.keys())[0] == "mate captain":
                            mateCaptainGrade.append(j.get("mate captain"))
                        if list(j.keys())[0] == "senior seaman":
                            seniorSeamanGrade.append(j.get("senior seaman"))
                        if list(j.keys())[0] == "ordinary seaman":
                            ordinarySeamanGrade.append(
                                j.get("ordinary seaman"))
                        if list(j.keys())[0] == "intern senior seaman":
                            internSeniorGrade.append(
                                j.get("intern senior seaman"))
                        if list(j.keys())[0] == "intern ordinary seaman":
                            internOrdinaryGrade.append(
                                j.get("intern ordinary seaman"))
                    if len(captainGrade) != 0:
                        captionDict = {
                            "captain": sum(captainGrade) / len(captainGrade)
                        }
                    else:
                        captionDict = {"captain": 0}
                    if len(chiefEngineerGrade) != 0:
                        chiefEngineerDict = {
                            "chief engineer":
                            sum(chiefEngineerGrade) / len(chiefEngineerGrade)
                        }
                    else:
                        chiefEngineerDict = {"chief engineer": 0}
                    if len(politicalCommissarGrade) != 0:
                        politicalCommissarDict = {
                            "political commissar":
                            sum(politicalCommissarGrade) /
                            len(politicalCommissarGrade)
                        }
                    else:
                        politicalCommissarDict = {"political commissar": 0}
                    if len(mateCaptainGrade) != 0:
                        mateCaptainDict = {
                            "mate captain":
                            sum(mateCaptainGrade) / len(mateCaptainGrade)
                        }
                    else:
                        mateCaptainDict = {"mate captain": 0}
                    if len(seniorSeamanGrade) != 0:
                        seniorSeamanDict = {
                            "senior seaman":
                            sum(seniorSeamanGrade) / len(seniorSeamanGrade)
                        }
                    else:
                        seniorSeamanDict = {"senior seaman": 0}
                    if len(ordinarySeamanGrade) != 0:
                        ordinarySeamanDict = {
                            "ordinary seaman":
                            sum(ordinarySeamanGrade) / len(ordinarySeamanGrade)
                        }
                    else:
                        ordinarySeamanDict = {"ordinary seaman": 0}
                    if len(internSeniorGrade) != 0:
                        internSeniorDict = {
                            "intern senior seaman":
                            sum(internSeniorGrade) / len(internSeniorGrade)
                        }
                    else:
                        internSeniorDict = {"intern senior seaman": 0}
                    if len(internOrdinaryGrade) != 0:
                        internOrdinaryDict = {
                            "intern ordinary seaman":
                            sum(internOrdinaryGrade) / len(internOrdinaryGrade)
                        }
                    else:
                        internOrdinaryDict = {"intern ordinary seaman": 0}
                    list2.append(captionDict)
                    list2.append(chiefEngineerDict)
                    list2.append(politicalCommissarDict)
                    list2.append(mateCaptainDict)
                    list2.append(seniorSeamanDict)
                    list2.append(ordinarySeamanDict)
                    list2.append(internSeniorDict)
                    list2.append(internOrdinaryDict)
                    list1.append(list2)
                # print(list1)

                totalHistoryGrade = []
                for i in list1:
                    delSet1 = set()
                    # 职位比较矩阵
                    positionWeight = np.array(configModel["positionWeight"],
                                              dtype=float)
                    if i[0].get("captain") == 0:
                        delSet1.add(0)
                    if i[1].get("chief engineer") == 0:
                        delSet1.add(1)
                    if i[2].get("political commissar") == 0:
                        delSet1.add(2)
                    if i[3].get("mate captain") == 0:
                        delSet1.add(3)
                    if i[4].get("senior seaman") == 0:
                        delSet1.add(4)
                    if i[5].get("ordinary seaman") == 0:
                        delSet1.add(5)
                    if i[6].get("intern senior seaman") == 0:
                        delSet1.add(6)
                    if i[7].get("intern ordinary seaman") == 0:
                        delSet1.add(7)
                    positionWeight = np.delete(np.delete(positionWeight,
                                                         list(delSet1),
                                                         axis=1),
                                               list(delSet1),
                                               axis=0)
                    # print(positionWeight)
                    # print(calculateWeight(positionWeight))
                    positionWeight_T = np.mat(
                        calculateWeight(positionWeight)).T
                    haveValueSet1 = {0, 1, 2, 3, 4, 5, 6, 7} - delSet1
                    historyGradeList = []
                    for j in haveValueSet1:
                        historyGradeList.append(i[j].get(
                            configModel["position"][j]))
                    historyGrade = (np.mat(historyGradeList) *
                                    positionWeight_T)[0, 0]
                    totalHistoryGrade.append(historyGrade)
                # 历史上各时期段分数
                # print(totalHistoryGrade)

                # 一个人的历史总成绩
                totalGrade = (np.mat(totalHistoryGrade) * timeWeightList_T)[0,
                                                                            0]
            else:
                totalGrade = 85
        insert = "replace into emp_history_totalgrade(EMP_NO, EMP_NAME, HISTORY_TOTAL_GRADE) values(" + "'" + model[
            "EMP_NO"] + "'," + "'" + model["EMP_NAME"] + "'," + str(
                totalGrade) + ")"
        cursor.execute(insert)
    conn.commit()
    conn.close()
Beispiel #6
0
def PersonGrade(personPath):
    # 读取公共配置(职位、职位权重之类)
    with open("../file/Common configuration/totalGradeCrewConfig.json"
              ) as json_model1:
        configModel = json.load(json_model1)

    # 读取船员个人成绩
    with open(personPath) as json_model2:
        model = json.load(json_model2)

    # 检验职位比较矩阵是否合理
    # testConsistency(np.array(configModel["positionWeight"], dtype=float))

    # 如果该船员不存在历史记录默认其历史分为85
    if not model["positionTimeGrade"]:
        return 85

    # 按时间从远到近排序,times列表
    times = sorted(model["positionTimeGrade"], reverse=True)
    # print(times)

    howManyYearsAgo = []
    for time in times:
        time = time.split("-")
        # 实际用当前年份
        howManyYearsAgo.append(datetime.datetime.now().year - int(time[0]))
        # 测试用2017(嘉祥山发生事故在2017年)
        # howManyYearsAgo.append(2017 - int(time[0]))
        # 测试用2018(安泰山发生事故在2018年)
        # howManyYearsAgo.append(2018 - int(time[0]))
        # 测试用2018(国投102发生事故在2018年)
        # howManyYearsAgo.append(2018 - int(time[0]))
    # print(howManyYearsAgo)

    # 和今年差0年一档,差1年一档,差2、3年一档,差4、5年一档,差6、7、8、9、10年一档,差10年以上一档
    timeWeight = np.array(configModel["timeWeight"], dtype=float)
    delSet = set()
    if 0 not in howManyYearsAgo:
        delSet.add(0)
    if 1 not in howManyYearsAgo:
        delSet.add(1)
    if 2 not in howManyYearsAgo and 3 not in howManyYearsAgo:
        delSet.add(2)
    if 4 not in howManyYearsAgo and 5 not in howManyYearsAgo:
        delSet.add(3)
    if 6 not in howManyYearsAgo and 7 not in howManyYearsAgo and 8 not in howManyYearsAgo and 9 not in howManyYearsAgo and 10 not in howManyYearsAgo:
        delSet.add(4)
    if max(howManyYearsAgo) <= 10:
        delSet.add(5)

    timeWeight = np.delete(np.delete(timeWeight, list(delSet), axis=1),
                           list(delSet),
                           axis=0)
    # print(timeWeight)
    # 根据timeWeight计算权重
    timeWeightList_T = np.mat(calculateWeight(timeWeight)).T
    # print(timeWeightList_T)

    # 找到存在的历史成绩档次的位置
    haveValueSet = {0, 1, 2, 3, 4, 5} - delSet
    # print(haveValueSet)

    moreTen = []
    sixToTenYears = []
    fourToFive = []
    twoTOThree = []
    one = []
    zero = []
    total = []
    for year in howManyYearsAgo:
        if year > 10:
            moreTen.append(year)
        if 6 <= year <= 10:
            sixToTenYears.append(year)
        if 4 <= year <= 5:
            fourToFive.append(year)
        if 2 <= year <= 3:
            twoTOThree.append(year)
        if year == 1:
            one.append(year)
        if year == 0:
            zero.append(year)
    total.append(zero)
    total.append(one)
    total.append(twoTOThree)
    total.append(fourToFive)
    total.append(sixToTenYears)
    total.append(moreTen)
    # print(total)

    # 将存储年份差的列表变成对应年份的职位和分数
    flag = 0
    for i in haveValueSet:
        for j in range(len(total[i])):
            total[i][j] = model["positionTimeGrade"][times[flag]]
            flag += 1
    # print(total)

    list1 = []
    for i in haveValueSet:
        captainGrade = []
        chiefEngineerGrade = []
        politicalCommissarGrade = []
        mateCaptainGrade = []
        seniorSeamanGrade = []
        ordinarySeamanGrade = []
        internSeniorGrade = []
        internOrdinaryGrade = []
        list2 = []
        for j in total[i]:
            if list(j.keys())[0] == "captain":
                captainGrade.append(j.get("captain"))
            if list(j.keys())[0] == "chief engineer":
                chiefEngineerGrade.append(j.get("chief engineer"))
            if list(j.keys())[0] == "political commissar":
                politicalCommissarGrade.append(j.get("political commissar"))
            if list(j.keys())[0] == "mate captain":
                mateCaptainGrade.append(j.get("mate captain"))
            if list(j.keys())[0] == "senior seaman":
                seniorSeamanGrade.append(j.get("senior seaman"))
            if list(j.keys())[0] == "ordinary seaman":
                ordinarySeamanGrade.append(j.get("ordinary seaman"))
            if list(j.keys())[0] == "intern senior seaman":
                internSeniorGrade.append(j.get("intern senior seaman"))
            if list(j.keys())[0] == "intern ordinary seaman":
                internOrdinaryGrade.append(j.get("intern ordinary seaman"))
        if len(captainGrade) != 0:
            captionDict = {"captain": sum(captainGrade) / len(captainGrade)}
        else:
            captionDict = {"captain": 0}
        if len(chiefEngineerGrade) != 0:
            chiefEngineerDict = {
                "chief engineer":
                sum(chiefEngineerGrade) / len(chiefEngineerGrade)
            }
        else:
            chiefEngineerDict = {"chief engineer": 0}
        if len(politicalCommissarGrade) != 0:
            politicalCommissarDict = {
                "political commissar":
                sum(politicalCommissarGrade) / len(politicalCommissarGrade)
            }
        else:
            politicalCommissarDict = {"political commissar": 0}
        if len(mateCaptainGrade) != 0:
            mateCaptainDict = {
                "mate captain": sum(mateCaptainGrade) / len(mateCaptainGrade)
            }
        else:
            mateCaptainDict = {"mate captain": 0}
        if len(seniorSeamanGrade) != 0:
            seniorSeamanDict = {
                "senior seaman":
                sum(seniorSeamanGrade) / len(seniorSeamanGrade)
            }
        else:
            seniorSeamanDict = {"senior seaman": 0}
        if len(ordinarySeamanGrade) != 0:
            ordinarySeamanDict = {
                "ordinary seaman":
                sum(ordinarySeamanGrade) / len(ordinarySeamanGrade)
            }
        else:
            ordinarySeamanDict = {"ordinary seaman": 0}
        if len(internSeniorGrade) != 0:
            internSeniorDict = {
                "intern senior seaman":
                sum(internSeniorGrade) / len(internSeniorGrade)
            }
        else:
            internSeniorDict = {"intern senior seaman": 0}
        if len(internOrdinaryGrade) != 0:
            internOrdinaryDict = {
                "intern ordinary seaman":
                sum(internOrdinaryGrade) / len(internOrdinaryGrade)
            }
        else:
            internOrdinaryDict = {"intern ordinary seaman": 0}
        list2.append(captionDict)
        list2.append(chiefEngineerDict)
        list2.append(politicalCommissarDict)
        list2.append(mateCaptainDict)
        list2.append(seniorSeamanDict)
        list2.append(ordinarySeamanDict)
        list2.append(internSeniorDict)
        list2.append(internOrdinaryDict)
        list1.append(list2)
    # print(list1)

    totalHistoryGrade = []
    for i in list1:
        delSet1 = set()
        # 职位比较矩阵
        positionWeight = np.array(configModel["positionWeight"], dtype=float)
        if i[0].get("captain") == 0:
            delSet1.add(0)
        if i[1].get("chief engineer") == 0:
            delSet1.add(1)
        if i[2].get("political commissar") == 0:
            delSet1.add(2)
        if i[3].get("mate captain") == 0:
            delSet1.add(3)
        if i[4].get("senior seaman") == 0:
            delSet1.add(4)
        if i[5].get("ordinary seaman") == 0:
            delSet1.add(5)
        if i[6].get("intern senior seaman") == 0:
            delSet1.add(6)
        if i[7].get("intern ordinary seaman") == 0:
            delSet1.add(7)
        positionWeight = np.delete(np.delete(positionWeight,
                                             list(delSet1),
                                             axis=1),
                                   list(delSet1),
                                   axis=0)
        # print(positionWeight)
        # print(calculateWeight(positionWeight))
        positionWeight_T = np.mat(calculateWeight(positionWeight)).T
        haveValueSet1 = {0, 1, 2, 3, 4, 5, 6, 7} - delSet1
        historyGradeList = []
        for j in haveValueSet1:
            historyGradeList.append(i[j].get(configModel["position"][j]))
        historyGrade = (np.mat(historyGradeList) * positionWeight_T)[0, 0]
        totalHistoryGrade.append(historyGrade)
    # 历史上各时期段分数
    # print(totalHistoryGrade)

    # 一个人的历史总成绩
    totalGrade = (np.mat(totalHistoryGrade) * timeWeightList_T)[0, 0]
    return int(totalGrade)