Ejemplo n.º 1
0
 def __init__(self, medicalWorkerID, patientID, appointmentID,
              appointmentDateTime, reason, prescription):
     Patient.__init__(self, patientID)
     GP.__init__(self, medicalWorkerID)
     self.appointmentID = appointmentID
     self.appointmentDateTime = appointmentDateTime
     self.reason = reason
     self.prescription = prescription
Ejemplo n.º 2
0
def VesselMapping(mappingfile, patient):
    # For each vessel/node in patient, map them to the same vessel in the mapping file.
    # For now, only 55 vessels are included.
    mapping = Patient.Patient()
    mapping.LoadVTPFile(mappingfile)
    mapping.Topology.UpdateVesselAtlas()
    for vessel in patient.Topology.Vessels:
        if vessel.ID < 56:  # no mapping beyond these vessels
            mappedvessel = mapping.Topology.VesselAtlas[vessel.ID]
            vessel.MajorVesselID = mappedvessel.MajorVesselID
            for node in vessel.Nodes:
                fractionalongvessellength = node.LengthAlongVessel / vessel.Length
                if vessel.ID == 15:  # starts at the vessel end
                    positioninmap = (1.0 - min(
                        1.0, fractionalongvessellength)) * mappedvessel.Length
                else:
                    positioninmap = min(
                        1.0, fractionalongvessellength) * mappedvessel.Length
                newposx = mappedvessel.InterpolationFunctions[0](positioninmap)
                newposy = mappedvessel.InterpolationFunctions[1](positioninmap)
                newposz = mappedvessel.InterpolationFunctions[2](positioninmap)
                node.SetPosition([newposx, newposy, newposz])
            # update the interpolation functions
            vessel.UpdateInterpolationFunctions()

    # update the bifurcation positions as well
    for bif in patient.Topology.BifurcationNodes:
        bif.SetPosition(next(iter(bif.Connections)).Position)
Ejemplo n.º 3
0
def addAppointmentDetails(doctordetail, patientdetail):

    data = json.load(open('Appoinment.json', 'r'))
    # data = {"appointment":[]}
    # data["appoinment"] = {}

    doctor_obj = Doctor()
    patient_obj = Patient()

    appointment_json = Appointment()
    appointment_json.set_doctor(doctordetail)
    appointment_json.set_patient(patientdetail)
    now = datetime.now()
    appointment_json.set_date(str(now)[:10])
    try:
        data["appointment"].append(
            {'doctor': appointment_json.get_doctor(), 'patient': appointment_json.get_patient(),
                'date': appointment_json.get_date()})

        with open('Appoinment.json', 'w') as data1:
            json.dump(data, data1, sort_keys=True)

        print ("Person Detail Added Successfully!")

    except (NameError, SyntaxError, TypeError):
        print "Please enter a proper formated data only !"
Ejemplo n.º 4
0
def MapMeshtoMSH(filevtp, filemsh, output="PialSurface.vtp"):
    """
    Apply the mapping on one surface to another surface.
    :param filevtp: The remeshed surface file, see the remesh function.
    :param filemsh: THe file containing the VEASL mapping.
    :param output: Filename of the resulting file.
    :return: Nothing
    """
    print("Mapping msh to vtp.")
    regionsIDs = [4, 21, 22, 23, 24, 25, 26, 30]
    patient = Patient.Patient()
    patient.Perfusion.LoadPrimalGraph(filevtp)
    centroids = patient.Perfusion.PrimalGraph.GetTriangleCentroids()

    msh = GeneralFunctions.MSHfile()
    msh.Loadfile(filemsh)
    positions, elements, indexes = msh.GetSurfaceCentroids(regionsIDs)

    sys.setrecursionlimit(10000)
    KDTree = scipy.spatial.KDTree(positions)
    MinDistance, MinDistanceIndex = KDTree.query(centroids, k=1)

    regiondict = GeneralFunctions.MajorIDdict_inv
    regionsIDs = [
        regiondict[elements[trianglenumber][3]]
        for index, trianglenumber in enumerate(MinDistanceIndex)
    ]
    patient.Perfusion.PrimalGraph.PolygonColour = regionsIDs
    patient.Perfusion.PrimalGraph.File = output
    patient.Perfusion.PrimalGraph.GraphToVTP("")
def add_appointment_details(doc_avail, pat_avail):
    data = json.load("Appointment.json", "r")

    doctor_obj = Doctor()
    patient_obj = Patient()

    appointment_doctor = Appointment()

    appointment_doctor.set_doctor(doc_avail)

    appointment_doctor.set_patient(pat_avail)

    now = datetime.now()

    appointment_doctor.set_date(str(now)[:10])

    try:
        data["appointment"].append({
            'doctor': appointment_doctor.get_doctor(),
            'patient': appointment_doctor.get_patient(),
            'date': appointment_doctor.get_date()
        })
        with open('Appointment.json', 'w') as database1:
            json.dump(data, database1, sort_keys=True)
        print("Details added successfully")

    except Exception:
        print("Data is not proper")
Ejemplo n.º 6
0
 def create(self, cmdLst):
   if cmdLst[1].lower() in ("patient", "personnel"):
     if type(cmdLst[2]) == str and type(cmdLst[3]) == str:
       if self.ifInt(cmdLst[4]):
         if cmdLst[1].lower() == "patient":
           try:
             sympLst = eval(cmdLst[5])
           except:
             print(">> La liste des symptomes doit être de type dictionnaire sans espaces !")
             print(">> exemple : {'toux':1,'fievre':5}\n")
           else:
             if type(sympLst) == dict:
               ok = True
               for sever in sympLst.values():
                 if not self.ifInt(sever) or not 1 <= sever <= 5:
                   ok = False
               if ok:
                 if len(sympLst) > 0:
                   self.patients.add(Patient(cmdLst[2].lower(), cmdLst[3].lower(), int(cmdLst[4]), cmdLst[5]))
                   self.patients.saveJson()
                 else:
                   print(">> Le patient doit au moins présenter un symptomes pour être admis !\n")
               else:
                 print(">> La structure de la liste des symptomes est incorrecte (la sévérité doit entre 1 et 5)\n")
         elif cmdLst[1].lower() == "personnel" and type(cmdLst[5]) == str:
           self.personnel.add(Personnel(cmdLst[2].lower(), cmdLst[3].lower(), int(cmdLst[4]), cmdLst[5].lower()))
           self.personnel.saveJson()
         else:
           print(">> Le role doit être de type text !\n")
       else:
         print(">> L'age doit être une valeur numérique !\n")
     else:
       print(">> Le nom et prénom doivent être de type text !\n")
   else:
     print(">> Le deuxième paramètre doit être : patient ou personnel !\n")
Ejemplo n.º 7
0
def simulationWithDrug(numTrials=20, numTimeSteps=500):
    """
    Run the simulation and plot the graph for problem 2 (no drugs are used,
    viruses do not have any drug resistance).
    Instantiates a patient, runs a simulation for 300 timesteps, and plots the
    total virus population as a function of time.
    """
    random.seed()

    # Virus Characteristics.
    maxPop = 1000
    numViruses = 100
    maxBirthProb = 0.1
    clearProb = 0.05
    resistances = {'guttagonol': False}
    mutProb = 0.005
    dataMatrix = numpy.zeros(shape=(numTrials, numTimeSteps))
    for trial in range(numTrials):

        # Model a random patient with the given virus charateristics.
        viruses = resistantVirusCollection(numViruses, maxBirthProb, clearProb,
                                           resistances, mutProb)
        randPatientX = Patient(viruses, maxPop)

        #Use drug on patient
        randPatientX.addPrescription('guttagonol')

        # Simulate the time-steps.
        dataMatrix[trial][0] = numViruses
        for time in range(1, numTimeSteps):
            dataMatrix[trial][time] = randPatientX.update()

    # Statistical Analysis.
    meanData = dataMatrix.mean(0)
    time = numpy.arange(numTimeSteps)
    stdData95_CI = dataMatrix.std(0) * 2
    selectedTime = numpy.arange(0, numTimeSteps, 10)

    # Ploting.
    pylab.plot(time, meanData)
    pylab.errorbar(time[selectedTime],
                   meanData[selectedTime],
                   stdData95_CI[selectedTime],
                   fmt='o')
    pylab.show()
Ejemplo n.º 8
0
    def doctorDetails(self):
        doctorInputName = input("Enter name: ")
        doctorInputAge = int(input("Enter age: "))
        doctorInputId = input("Enter patient Id: ")
        doctorInputAddress = input("Enter address: ")

        doctorObject = Patient(doctorInputName, doctorInputAge, doctorInputId,
                               doctorInputAddress)
        self.doctorList.append(doctorObject)
Ejemplo n.º 9
0
 def patientDetails(self):
     patientInputName = input("Enter name: ")
     patientInputAge = int(input("Enter age: "))
     patientInputId = input("Enter patient Id: ")
     patientInputAddress = input("Enter address: ")
     patientInputVisits = int(input("Enter number of visits: "))
     patientObject = Patient(atientInputName, patientInputAge,
                             patientInputId, patientInputAddress,
                             patientInputVisits)
     self.patientList.append(patientObject)
Ejemplo n.º 10
0
def newPatient(name, contact, email, loc, time, query):
    patient = P.Patient(name, contact, email, loc, time, query)

    if query == "Emergency":
        emergency(patient)
    elif query == "Online Consultancy":
        onlineConsult(patient)
    elif query == "Later Appointment":
        forAppointment(patient)
    makeAppointment(patient, hospital1, "Fatan Singh")
Ejemplo n.º 11
0
def ConvertBravaSet(path):
    Dataset_SWC_To_VTP(path)

    # one file seems to be rotated with respect to the others
    with contextlib.redirect_stdout(None):
        file = path + "Set8_ColorCoded.CNG.vtp"
        patient = PatientModule.Patient()
        patient.LoadVTPFile(file)
        totalmatrix = GeneralFunctions.TMatrix(1, [0, 0, 180], [0, 0, 0])
        GeneralFunctions.TransformFile(file, totalmatrix)
Ejemplo n.º 12
0
    def get_all_patients(self):
        res = requests.get('{}/Patient'.format(self.__FHIR_BASE_URL), headers=self.__auth_header)
        json = res.json()
        result = self.__get_all_patients_page(json, [])

        patients = []
        for patient_json_data in result:
            for patient_data in patient_json_data["entry"]:
                patients.append(Patient.Parse_Patient().verify_json(patient_data))
        print(len(patients))
        return patients
Ejemplo n.º 13
0
def SWC_Processing1d(filename):
    """
    Convert a .swc file to a .vtp file
    Note that this assumes a particular order and meaning of the columns
    """
    print("Converting swc file.")
    newname = filename[:-3] + "vtp"
    dataset = [text.split() for text in open(filename)]

    number = [int(line[0]) for line in dataset]
    colour = [int(line[1]) for line in dataset]
    positions = [[float(line[2]),
                  float(line[3]),
                  float(line[4])] for line in dataset]
    radius = [float(line[5]) for line in dataset]
    connection = [int(line[6]) for line in dataset]

    links = [[] for node in range(0, len(number))]
    for i in range(0, len(number)):
        if connection[i] > 0:
            nodenumber = number[i] - 1
            linkedto = connection[i] - 1
            links[nodenumber].append(linkedto)
            links[linkedto].append(nodenumber)

    nodes = [Node() for node in range(0, len(number))]
    [nodes[index].SetRadius(rad) for index, rad in enumerate(radius)]
    [nodes[index].SetPosition(pos) for index, pos in enumerate(positions)]
    [nodes[index].SetMajorVesselID(c) for index, c in enumerate(colour)]

    for index, link in enumerate(links):
        for con in link:
            nodes[index].AddConnection(nodes[con])

    patient = PatientModule.Patient()
    patient.Topology.Nodes = nodes
    patient.Topology.AnatomyToVessels()
    vesseltype = [
        colour[patient.Topology.Nodes.index(vessel.Nodes[1])]
        for vessel in patient.Topology.Vessels
    ]
    patient.Topology.VesselAtlas = vesseltype

    pos = [node.Position for node in patient.Topology.Nodes]
    meanx = numpy.mean([p[0] for p in pos])
    meany = numpy.mean([p[1] for p in pos])
    meanz = numpy.mean([p[2] for p in pos])
    centermatrix = GeneralFunctions.TMatrix(1, [90, 0, 0],
                                            [-meanx, -meany, -meanz])
    patient.Topology.ApplyTransformation(centermatrix)

    patient.Topology.TopologyToVTP(newname)
    return patient
Ejemplo n.º 14
0
    def get_all_patients(self):
        res = requests.get('{}/Patient'.format(self.__FHIR_BASE_URL),
                           headers=self.__auth_header)
        json = res.json()
        result = self.get_patients_list(json, [])

        patients = []
        for patient_json_data in result:
            for patient_data in patient_json_data["entry"]:
                patients.append(
                    Patient.Create_Patient().Test_Jsonfile(patient_data))
        return patients
Ejemplo n.º 15
0
 def __init__(self, name, address):
     self.rawAN24= AN24.AN24(address)
     self.patient = Patient.Patient()
     self.address = address
     self.name = name
     self.all_battry_time = 10.0
     self.rest_battry_time = 0
     self.start_time = 0               
     self.draw_current_time = 0
     self.is_detecting = False
     self.is_connected = False
     self.is_checked = False
     self.end_count_pre = 0        
Ejemplo n.º 16
0
 def __init__(self):
     self.file = open('cache.txt', 'at')
     self.file = open('cache.txt')
     patients = [line for line in self.file.read().split('\n')]
     self.patients = []
     for patient in patients:
         try:
             ssn = patient.split(':;')[1]
             a = Patient(ssn)
             self.patients.append(a)
         except IndexError:
             pass
     self.file = open('cache.txt', 'at')
Ejemplo n.º 17
0
def initialize():
    DATABASE.connect()
    DATABASE.create_tables([
        Personnel, Patient, Medicine, Prescription, Appointment, Room, Roomuse
    ],
                           safe=True)
    DATABASE.close()
    app = appt.Appointment("ap0001")
    pats = pat.Patient("AS")
    date = datetime.datetime(2016, 1, 12, 4, 50, 30, 100, None)
    app.create("1234", date, 1, 1, 1, "1000", "DIE")
    pats.create(1, "Por", date, "0818188216", 10, "AS", "AS")
    pers = person.Personnel(1)
    pers.create(1, "PO", "a", "b", "c")
Ejemplo n.º 18
0
 def __init__(self, uuid, name):
     self.data_handler = DataHandler.DataHandler()
     self.patient = Patient.Patient()
     self.uuid = uuid
     self.name = name
     self.name = name
     self.all_battry_time = 10.0
     self.rest_battry_time = 0
     self.start_time = 0
     self.draw_current_time = 0
     self.is_detecting = False
     self.is_infoed = False
     self.is_connected = False
     self.is_checked = False
     self.end_count_pre = 0
Ejemplo n.º 19
0
def setup():
    # Setup keys and clean Database
    db1 = Database()
    db1.reset()
    proxy = Proxy()
    signGroup = PairingGroup('SS512') #Possibly the same as for encryption
    waters = pksig_waters.WatersSig(signGroup)
    (masterPK, masterSK) = waters.setup(5) #master pub and priv keys for signing (other keys are deduced from the master secret key)

    # Insert the master public key to the db with SignKeys.id="master", it is needed for signing and verifying
    # masterSK (secret key) gets passed only to the signKeyGen function below
    # db1.insertSignKey("master", objectToBytes(masterPK, signGroup))

    # Create some identities (names). Do NOT use the same identity twice! It will destroy the signature scheme implementation.
    id1 = "Alice"
    id2 = "AIG Insurance"           # Insurance
    id3 = "Fitness First"           # Health Club
    id4 = "Catherina Ziekenhuis"    # Hospital
    id4 = "Madison Gurkha"          # Employer
    id5 = "Doctor Frankenstein"     # Doctor

    # Create keys for all id's and store the public part in the database under SignKeys.pubKey with the PatientID or EntityID in SignKeys.id
    id1_signK = signKeyGen(id1, masterSK, masterPK, waters, signGroup, db1)
    id2_signK = signKeyGen(id2, masterSK, masterPK, waters, signGroup, db1)
    id3_signK = signKeyGen(id3, masterSK, masterPK, waters, signGroup, db1)
    id4_signK = signKeyGen(id4, masterSK, masterPK, waters, signGroup, db1)
    id5_signK = signKeyGen(id5, masterSK, masterPK, waters, signGroup, db1)


    # Instantiate the patients and entities
    Alice = Patient(id1, proxy, id1_signK, signGroup, waters, masterPK)
    AIG = Entity(id2, proxy, id2_signK, signGroup, waters, masterPK)
    FitnessFirst = Entity(id3, proxy, id3_signK, signGroup, waters, masterPK)
    Ziekenhuis = Entity(id4, proxy, id4_signK, signGroup, waters, masterPK)
    Doctor = Entity(id5, proxy, id5_signK, signGroup, waters, masterPK)


    # Patient inserting (encrypted) information into her own Medical Record
    msg1 = "Blood Type A+"
    msg2 = "Height 1.75m"
    msg3 = "Weight 60 kg"
    msg4 = "Surgery to remove xxx on 16/05/2010"
    msg5 = "Yoga practice 1 hr on 24/10/2013"
    Alice.store("General", msg1)
    Alice.store("General", msg2)
    Alice.store("General", msg3)
    Alice.store("Medical", msg4)
    Alice.store("Training", msg5)

    return proxy, Alice, AIG, FitnessFirst, Ziekenhuis, Doctor
Ejemplo n.º 20
0
 def __init__(self, name, address):
     self.rawAN24 = AN24.AN24({name: address})
     self.handler = Handler(self.rawAN24._uuid, self.rawAN24._name)
     self.patient = Patient.Patient()
     self.address = address
     self.name = name
     self.all_battry_time = 10.0
     self.rest_battry_time = 0
     self.start_time = 0
     self.draw_current_time = 0
     self.is_detecting = False
     self.is_infoed = False
     self.is_connected = False
     self.is_checked = False
     self.end_count_pre = 0
     self.note = []
Ejemplo n.º 21
0
 def __init__(self, name, address, temp_socket):
     self.rawAN24 = temp_socket
     self.handler = Handler(self.rawAN24._uuid, self.rawAN24._name)
     self.patient = Patient.Patient()
     self.address = address
     self.name = name
     self.all_battry_time = 10.0
     self.rest_battry_time = 0
     self.start_time = 0
     self.draw_current_time = 0
     self.is_detecting = False
     self.is_infoed = False
     self.is_connected = False
     self.is_checked = False
     self.end_count_pre = 0
     self.note = []
     self.is_alarmed = False
     self.is_alarm = False
     self.disable_alarm_count = 0
Ejemplo n.º 22
0
def Sim(num_patients, mHealth):
    #Each loop represents a new patient
    for i in range(num_patients):
        """
        Random sampling a new age, hui, and hba1c for every loop.
        """
        age = np.random.randint(18, 40)  # random integer between 18 and 60
        hui = round(np.random.uniform(.7, .9), 2)  #random health utility index
        hba1c = round(np.random.uniform(6.5, 14), 2)  #random hba1c %
        patient = p.Patient(age, hui, hba1c)  #patient instance
        """
        1 quarter = 3months. 40 quarters = 10 years
        choose quarter because HbA1c levels change every 3 months
        """
        quarter = 0
        print("starting age= " + str(patient.age))
        while True:
            q_init = patient.hba1c  #HbA1c at the beggining of the quarter
            q_final = patient.q_update(
                patient.hba1c, patient.hui,
                mHealth)  #HbA1c at the end of the quarter
            quarter += 1
            #If the change in HbA1C is between 0.8 and 1.2 and +ive (means it increased), decrease HUI
            if 0.8 <= abs(q_final - q_init) <= 1.2 and q_final - q_init > 0:
                patient.hui += -0.03
            if quarter % 4 == 0:  #If a year has passed
                compl = patient.det_complication(
                    patient.hba1c)  #determine the complication penalty
                patient.hui += compl  # add complication penalty to HUI
                #print("complication is : " + str(compl))
                patient.age += 1
            #While loop break conditions
            if quarter == 120 or patient.hui <= 0 or patient.age >= 90:
                break

        #print('quarter = ' + str(quarter))
        print("patient age =" + str(patient.age))
        print("patient hui =" + str(round(patient.hui, 2)))
        print("patient hba1c =" + str(patient.hba1c))
Ejemplo n.º 23
0
def Sim(num_patients, mHealth):
    #Each loop represents a new patient
    for i in range(num_patients):
        """
        Generating a new age, hui, and hba1c for every loop.
        """
        age = np.random.randint(18, 40)  # random integer between 18 and 60
        hui = round(np.random.uniform(.7, .9), 2)  #random health utility index
        hba1c = round(np.random.uniform(6.5, 14), 2)  #random hba1c %
        patient = p.Patient(age, hui, hba1c)  #patient instance
        """
        1 quarter = 3months. 40 quarters = 10 years
        choose quarter because HbA1c levels change every 3 months
        """
        quarter = 0
        print("starting age= " + str(patient.age))
        while patient.hui > 0.1 and quarter < 400 and patient.age < 100:
            q_hba1c = patient.hba1c + round(np.random.uniform(-0.5, 1.0),
                                            2)  # random change in Hba1C
            # 1% change during quarter visit and HbA1C increased
            if 0.9 <= abs(q_hba1c - patient.hba1c
                          ) <= 1.1 and q_hba1c - patient.hba1c > 0:
                patient.hui += -0.03


#            elif patient.hui < 1:
#                patient.hui+= 0.03
            if quarter % 4 == 0:  #year has passed
                patient.age += 1
            quarter += 1
            if 6.5 < q_hba1c < 20:  #capping hba1c at 20
                patient.hba1c = q_hba1c

        print("patient age =" + str(patient.age))
        print("patient hui =" + str(patient.hui))
        print("patient hba1c =" + str(patient.hba1c))
Ejemplo n.º 24
0
def problem3_delayedTreatment(numTrials=20,
                              delayTimeSteps=300,
                              treatmentSteps=150):
    """
    Runs simulations and make histograms for problem 5.

    Runs multiple simulations to show the relationship between delayed treatment
    and patient outcome.

    Histograms of final total virus populations are displayed for delays of 300,
    150, 75, 0 timesteps (followed by an additional 150 timesteps of
    simulation).
    """
    random.seed()

    # Virus Characteristics.
    maxPop = 1000
    numViruses = 100
    maxBirthProb = 0.1
    clearProb = 0.05
    resistances = {'guttagonol': False}
    mutProb = 0.005
    dataMatrix = numpy.zeros(shape=(numTrials,
                                    delayTimeSteps + treatmentSteps))
    finalCount = []
    for trial in range(numTrials):
        if trial % 50 == 0: print trial + 1

        # Model a random patient with the given virus charateristics.
        viruses = resistantVirusCollection(numViruses, maxBirthProb, clearProb,
                                           resistances, mutProb)
        randPatientX = Patient(viruses, maxPop)

        # wait before adminstering drug.
        dataMatrix[trial][0] = numViruses
        for time in range(1, delayTimeSteps):
            dataMatrix[trial][time] = randPatientX.update()

        #Use drug on patient
        randPatientX.addPrescription('guttagonol')

        # wait for drug effects.
        for time in range(delayTimeSteps, delayTimeSteps + treatmentSteps):
            dataMatrix[trial][time] = randPatientX.update()

        finalCount.append(dataMatrix[trial][delayTimeSteps + treatmentSteps -
                                            1])

    # Statistical Analysis.
    meanData = dataMatrix.mean(0)
    time = numpy.arange(delayTimeSteps + treatmentSteps)
    stdData95_CI = dataMatrix.std(0) * 2
    selectedTime = numpy.arange(0, delayTimeSteps + treatmentSteps, 10)

    # Plotting.
    n, bins, patches = pylab.hist(finalCount, 100, facecolor='red')
    pylab.xlabel('Virus Population After 50 Steps of Drug Use')
    pylab.ylabel('Number of Patients')
    pylab.title('Effect of Delayed Treatment - Delay : ' +
                str(delayTimeSteps) + ' Steps')
    pylab.show()
Ejemplo n.º 25
0
 def addPatient(self, name, dob):
     p = Patient(name, dob)
     self.unassignedPatients.append(p)
     return p
Ejemplo n.º 26
0
def main():
    print("Symptom prediction Experiment")
    global variable_file
    print("Connecting to ML4H DB..")

    conn = pymysql.connect(host='nightmare.cs.uct.ac.za',
                           port=3306,
                           user='******',
                           passwd='oesaerex',
                           db='ochomo001')

    print("Connected")

    cur = conn.cursor()
    print("Executing SQL query..")
    print(
        "SQL Script: select * from ML4H_symptom_totals a inner join ML4H_most_recent_symptom_days_limit b on a.person_id=b.person_id"
    )
    print("Retrieving symptom features in sql query...")
    #Query to get the totals of all the symptoms and amount of days since last reporting of a symptom
    # that a patient has reported to the clinic
    #Used as features to predict the next possible that a patient will report
    cur.execute(
        "select * from ML4H_symptom_totals a inner join ML4H_most_recent_symptom_days_limit b on a.person_id=b.person_id"
    )
    print("Executed")
    cur.close()

    #Loading features
    patient_ids = []
    sum_of_features = []
    for k in range(len(
            Patient.features)):  #Counter for the occurences of symptoms
        sum_of_features.append(0)

    patients = {}
    print("loading in data into program...")
    for row in cur:
        if (row[0] not in patient_ids):  #Create patient if haven't already
            patient_ids.append(row[0])
            patients[row[0]] = (Patient(int(row[0])))

        #Set the patients feature array to the retrieved features
        patients[row[0]].feature_symptom_array = [
            int(row[2]) + int(row[10]),
            int(row[3]),
            int(row[4]),
            int(row[5]),
            int(row[6]),
            int(row[7]),
            int(row[8]),
            int(row[9]),
            int(row[11]),
            int(row[12]),
            int(row[13]),
            int(row[14]),
            int(row[15]),
            int(row[16]),
            int(row[17]), 0, 0, 0,
            int(row[21]),
            int(row[22]),
            int(row[23]),
            int(row[24]),
            int(row[25]),
            int(row[26]),
            int(row[27]),
            int(row[28]),
            int(row[29]),
            int(row[30]),
            int(row[31]),
            int(row[32]),
            int(row[33]),
            int(row[34]),
            int(row[35])
        ]
        #To check the balance of features
        for i in range(len(sum_of_features) - 3):
            if i == 8:  #Exception for Cough for duration - joining with Cough feature
                sum_of_features[0] += int(row[i + 2])
            elif i == 16 or i == 17 or i == 18:  #Exceptions for the patient demographic features (added later)
                continue
            elif i > 8:
                sum_of_features[i - 1] += int(row[i + 2])
            else:
                sum_of_features[i] += int(row[i + 2])

    cur1 = conn.cursor()
    print("Executing SQL query..")
    print(
        "SQL script: select person_id, value_coded_name_id,name, MAX(obs_datetime) from Obs_artvisit_sympt a inner join concept_name n on a.value_coded_name_id = n.concept_name_id where value_coded_name_id IN (524,110,4315,156,3,888,11335,17,2325,4407,10894,9345,838,4355,11333) Group by person_id"
    )
    print("Getting the last symptom reported for the result set...")
    #Gets the last reported symptom that a patient reported - RESULT CLASS (Trying to predict this)
    cur1.execute(
        "select person_id, value_coded_name_id,name, MAX(obs_datetime) from Obs_artvisit_sympt a inner join concept_name n on a.value_coded_name_id = n.concept_name_id where value_coded_name_id IN (524,110,4315,156,3,888,11335,17,2325,4407,10894,9345,838,4355,11333) Group by person_id"
    )
    print("Executed")
    cur1.close()

    #Loads result set - last symptom reported by patient
    for row in cur1:
        if row[2] == "None" or row[2] == 'None' or row[2] is None:
            continue
        if (row[0] in patient_ids):
            if row[2] == "Cough of any duration":
                patients[row[0]].last_symptom = "Cough"
            else:
                patients[row[0]].last_symptom = row[2]
            patients[row[0]].set_sympt_class(
            )  #Indexing - Binaryzing classes for ROC scores later on

    print("Loaded data")
    print()

    # Adding temporal aspect and adding more patient specific  - Sex, Age, Last Drug, num of symptoms in prev month
    # If last reported symptom is longer than a specified number of days(eg. 30) then change result to No symptom
    # Reason: Too long after to be helpful i.e predicting that someone will eventually report a skin rash is not as helpful
    # as predicting a skin rash next month.
    print("Executing temporal query...")
    print("SQL script: select * from ML4H_symptom_resultset")
    print(
        "Retrieving patient demographic info and changing last symptom report to "
        "No symptom if last reported symptom is longer than 40 days..")
    cur4 = query_for_40_day_prev_symptoms_FROM_TABLE(conn)
    for row in cur4:
        if (row[0] in patient_ids):
            if int(row[3]) < 41 and patients[row[0]].last_symptom != "None":
                patients[row[0]].last_symptom = "No symptoms"
                patients[row[0]].set_sympt_class(
                )  # Reindexing - Binaryzing classes for ROC scores later on
            patients[row[0]].feature_symptom_array[Patient.features.index(
                "Age")] = int(row[5].year)
            patients[row[0]].feature_symptom_array[Patient.features.index(
                "Last Drug")] = int(row[6])
            patients[row[0]].feature_symptom_array[Patient.features.index(
                "Tot Prev Month Symptoms")] = int(row[7])

    print("Executed.")

    conn.close()

    #Load all data into arrays for ML application
    ml4hX = []
    ml4hY = []
    ml4hY_multiclass = []
    for id in patient_ids:
        if patients[id].check_if_null_features(
        ):  #If any features null then Machine learning can't handle
            continue
        if patients[id].last_symptom == "None":
            continue
        if patients[id].feature_symptom_array[Patient.features.index(
                "Age")] == 0:  #Means age is incorrect
            continue
        ml4hX.append(patients[id].feature_symptom_array)
        ml4hY.append(patients[id].last_symptom)
        ml4hY_multiclass.append(
            patients[id].last_symptom_class)  #Numeric verson of result set

    print()
    print("Length of Feature array: " + str(len(ml4hX)))
    print("Length of ResultSet array: " + str(len(ml4hY)))

    # Opening significance file for writing
    variable_file = open("symptom_variable_significance.csv", 'w')
    for symptom in Patient.features:
        variable_file.write("," + symptom)
    variable_file.write("\n")

    print("Orig")
    check_symptom_result_distribution(ml4hY)
    print()
    #Split training and hold out set
    X_train1, X_validation1, Y_train1, Y_validation1 = model_selection.train_test_split(
        ml4hX, ml4hY_multiclass, test_size=0.37, random_state=11)

    #Check the new balances of the classes
    print("Y_train")
    check_symptom_result_distribution(Y_train1)
    print("Y_Validation")
    check_symptom_result_distribution(Y_validation1)

    # APPLYING MACHINE LEARNING TECHNIQUES WITH THE NEARMISS BALANCED DATASET (NearMiss proven to be best balanced)
    X_cha, Y_cha = NearMiss(ratio=0.015,
                            n_neighbors=2).fit_sample(X_train1, Y_train1)
    check_symptom_result_distribution(Y_cha)
    X_fitted_higher, Y_fitted_higher = RandomOverSampler().fit_sample(
        X_cha, Y_cha)  #Oversample to bring classes up
    #Apply machine learning techniques with the balanced dataset and write results to Adjusted file
    apply_machine_learning_techniques(X_fitted_higher, Y_fitted_higher,
                                      "Adjusted", X_validation1, Y_validation1)

    #Print distributions of features and result classes
    print("feature distribution")
    for j in range(len(sum_of_features)):
        print(Patient.features[j] + " : " + str(sum_of_features[j]))

    print()
    print("result class distribution")

    check_symptom_result_distribution(ml4hY)
    variable_file.close()
Ejemplo n.º 27
0
import Authentication
import diagnosis
import Patient

auth = Authentication.Authentication()
db = Authentication.Database()
diag = diagnosis.Diagnosis()

patient = Patient.PatientInfo()


class Hrm:
    email = ""
    password = ""

    doctor_details = {
        "doctors_name": " ",
        "doctors_specialization": " ",
        "hospital_name": " ",
    }

    def greet(self):
        print("Hello Doctor!!!!")

    def ask_for_user_choice(self):
        print("Do you want to login or register ?")
        choice = input("Enter: \n 1 : Login \n 2 : Register \n ")
        if int(choice) == 1:
            self.ask_for_user_data()
            self.login_user()
        elif int(choice) == 2:
Ejemplo n.º 28
0
def blood_flow_script(executable, patient_folder, clot_present):
    Patient = PatientModule.Patient(patient_folder)
    # remove result files if these were created during a previous run
    Patient.RemoveOldSimFiles()
    Patient.LoadBFSimFiles()

    # if not os.path.exists(resultsfolder):
    #     os.mkdir(resultsfolder)
    model = "Pulsatile"
    # model = "Steady"
    resultsfolder = Patient.Folders.ModellingFolder
    if model == "Pulsatile":
        if clot_present == "true" or clot_present == "True":
            subprocess.call([
                "mono", executable, resultsfolder + "Run.txt",
                resultsfolder + "Results.dyn", resultsfolder + "Clots.txt"
            ])
        else:
            subprocess.call([
                "mono", executable, resultsfolder + "Run.txt",
                resultsfolder + "Results.dyn"
            ])
        Patient.LoadResults("Results.dyn", correct=False)
        # BloodflowEquations.Bloodflow1D(Patient)
    else:
        Patient.Initiate1DSteadyStateModel()
        if clot_present == "True" or clot_present == "true":
            Patient.Run1DSteadyStateModel(model="Linear", clotactive=True)
        else:
            Patient.Run1DSteadyStateModel(model="Linear", clotactive=False)

        # export data
        TimePoint = Results.TimePoint(0)
        TimePoint.Flow = [node.FlowRate for node in Patient.Topology.Nodes]
        TimePoint.Pressure = [node.Pressure for node in Patient.Topology.Nodes]
        TimePoint.Radius = [node.Radius for node in Patient.Topology.Nodes]

        TimePoint2 = Results.TimePoint(
            Patient.ModelParameters['Beat_Duration'])
        TimePoint2.Flow = TimePoint.Flow
        TimePoint2.Pressure = TimePoint.Pressure
        TimePoint2.Radius = TimePoint.Radius

        Patient.Results.TimePoints = [TimePoint, TimePoint2]
        Patient.Results.ExportResults(resultsfolder + "Results.dyn")

        Patient.LoadResults("Results.dyn")

    Patient.GetMeanResults()
    Patient.ExportMeanResults()

    # depending on triangles or vertexes
    # Patient.DistributeFlowVertex()
    Patient.DistributeFlowTriangles()
    Patient.ExportTriangleFlowData()

    Patient.WriteTimeseriesVessels()
    Patient.Results.AddResultsPerNodeToFile(Patient.Folders.ModellingFolder +
                                            "Topology.vtp")
    Patient.Results.AddResultsPerVesselToFile(Patient.Folders.ModellingFolder +
                                              "Topology.vtp")

    # add results to the mesh used in the perfusion model
    # file1 = Patient.Folders.ModellingFolder + "FlowDistributedMean.vtp"
    # clusteringflowdata = Patient.Folders.ModellingFolder + "ClusterFlowData.csv"
    # filehighres = Patient.Folders.ModellingFolder + "labelled_vol_mesh.msh"
    # GeneralFunctions.MapClusteringToMSH(file1, filehighres, clusteringflowdata, Patient.Folders.ModellingFolder)

    # update the flow to the perfusion model
    clusteringflowdata = Patient.Folders.ModellingFolder + "ClusterFlowData.csv"
    clusteringfile = Patient.Folders.ModellingFolder + "Clusters.csv"
    datafolder = Patient.Folders.ModellingFolder
    GeneralFunctions.WriteFlowFilePerfusionModel(clusteringflowdata,
                                                 clusteringfile, datafolder)
Ejemplo n.º 29
0
        plots.append(Plot(data[0], data[1]))

with open('paramedic.txt', 'r') as file:
    file_input = file.readlines()
    index_plot = 0
    for data in read_file(file_input):
        paramedics.append(
            Paramedic(data[0], data[1], data[2], data[3], data[4],
                      plots[index_plot], data[5], data[6], data[7]))
        index_plot += 1

with open('patient.txt', 'r') as file:
    file_input = file.readlines()
    for data in read_file(file_input):
        patients.append(
            Patient(data[0], data[1], data[2], data[3], data[4], data[5],
                    data[6], data[7]))

print('\nСписки пациентов, обслуживаемых данным врачом:')
select_doctor = paramedics[2]
for doctor in paramedics:
    if select_doctor.plot.address == doctor.plot.address:
        for person in patients:
            if select_doctor.plot.address == person.address:
                print(person)

print('\nСколько медсестер на каждом участке:')
for doctor in paramedics:
    if doctor.special == 'medsister':
        print(doctor.plot, ' - 1')
    else:
        print(doctor.plot, ' - 0')
Ejemplo n.º 30
0
def makePatient(name, birth, gender, ethnicity, language, roomNumber, school,
                screeningComment, referral):
    return Patient(name, birth, gender, ethnicity, language, roomNumber,
                   school, screeningComment, referral)
Ejemplo n.º 31
0
                cv.RGB(255,0,0),1,8,0)
    """


######################Testing ######################

if (TEST):
    # The following code replicates calls from the UI layer
    print "Making patient object..."

    # Horizontal photos have the eyes along a horizontal axis
    horiz = os.path.dirname(os.path.abspath(sys.argv[0]))
    horiz += "/pics/homemade/jthorizontal.jpg"
    vert = os.path.dirname(os.path.abspath(sys.argv[0]))
    vert += "/pics/homemade/andrewvertical.jpg"
    patient = setPatient(horiz, vert, Patient())

    # Take the horizontal image and draw bounding eye boxes
    horizontalPhoto = patient.getHorizontal()

    # Reset the eye regions and pupil regions
    # print "Resetting the eye regions and the pupil regions..."
    resetEyes(patient, ((455, 572, 647, 695), (771, 537, 958, 650)),
              ((467, 596, 620, 718), (746, 614, 887, 704)))
    #resetEyes (patient, ((1,10,20,30), (2,11,21,32)), ((101,102,140,156), (123,141,202,200)))

    # Pass in pupil coordinates relative to the eye photo
    #resetPupils( patient, ((93,64,17),(91,62,19)) , ((33,32,8 ),(32,28,8)) )
    #resetEyes( patient, ((100,100,150,150),(150,150,200,200)) , ((101,101,151,151),(151,151,201,201)) )

    # negative value