def generate_isolates(self):

        for isolate in config.ISOLATE_LIST:

            # Randomly select an individual
            random_individual = self.get_random_individual()
            random_individual_id = random_individual.id

            # Randomly select a sample type
            sample_type = random.choice(config.ISOLATE_SAMPLE_TYPE)

            # Generate an isolate id
            isolate_id = isolate

            # Is the randomly selected individual an in patient
            if random_individual_id < len(self.movement.individual_list):

                # randomly select a date within the individuals admissions
                # Random admission
                random_admission = random.choice(random_individual.admission_list)

                random_date = radar.random_date(
                    start=random_admission.admission_date,
                    stop=random_admission.discharge_date,
                )

                building_sent_from_name = config.ISOLATE_IN_PATIENT_SAMPLE_BUILDING
                building_sent_from_location = "unkown"

            # Otherwise the individual is an outpatient
            else:

                # Generate a random date
                random_date = radar.random_date(
                    start=config.DATE_START,
                    stop=config.DATE_END
                )

                building_sent_from = random.choice(config.ISOLATE_OUT_PATIENT_SAMPLE_BUILDING)

                building_sent_from_name = building_sent_from.get('name')
                building_sent_from_location = random.choice(building_sent_from.get('locations'))

            # Randomly select an antibiogram result set
            random_antibiogram = self.antibiogram.choose_random_antibiogram()

            new_isolate = Isolate(isolate_id)
            new_isolate.individual_id = random_individual_id
            new_isolate.sample_type = sample_type
            new_isolate.sample_description = random.choice(config.ISOLATE_SAMPLE_DESCRIPTION)
            new_isolate.date_sent = random_date
            new_isolate.sent_from_location = building_sent_from_location
            new_isolate.sent_from_name = building_sent_from_name
            new_isolate.antibiogram = random_antibiogram

            #mapped_antibiogram = self.antibiogram.get_antibiogram_map(random_antibiogram, ANTIBIOGRAM_ANTIBIOTICS)

            self.isolate_list.append(new_isolate)
def insert_treatment_plan_1(n, doc_ssn1, doc_snn_2, pat_snn1, pat_snn_2):
    inserts = "INSERT INTO Treatment_plan (id, doctor_ssn, patient_ssn, discharge_date, hospitalization_date, diagnoses, procedures) VALUES \n"
    for k in range(n):
        diagnoses = random.choice(list(random_data.treatments.keys()))
        inserts += "({}, {}, {}, '{}', '{}', '{}', '{}'),\n".format(
            k, random.randint(doc_ssn1, doc_snn_2 - 1),
            random.randint(pat_snn1, pat_snn_2 - 1),
            radar.random_date(start=datetime.date(year=2014, month=5, day=24),
                              stop=datetime.date(year=2015, month=5, day=24)),
            radar.random_date(start=datetime.date(year=2012, month=5, day=24),
                              stop=datetime.date(year=2013, month=5, day=24)),
            diagnoses, random.choice(random_data.treatments[diagnoses]))

    inserts = inserts[:-2] + ';\n'
    return inserts
Esempio n. 3
0
 def test_02_random_date(self):
     """
     Test ``radar.random_datetime``.
     """
     res = radar.random_date()
     self.assertTrue(isinstance(res, datetime.date))
     return res
Esempio n. 4
0
def generate_dates(time_slices, forecast_windows, start_date, end_date,
                   load_prev_files, output_slices_path):
    if load_prev_files and os.path.exists(output_slices_path):
        with open(output_slices_path, "rb") as prev_slices:
            dataset_slices = pickle.load(prev_slices)
        return dataset_slices
    elif type(time_slices) is list:
        dataset_slices = time_slices
        with open(output_slices_path, "wb+") as save_path:
            pickle.dump(dataset_slices, save_path)
        return dataset_slices
    else:
        forecast_windows = [timedelta(weeks=x * 52) for x in forecast_windows]
        largest_window = max(forecast_windows)
        effective_end_date = end_date - largest_window
        feature_slices = [
            random_date(start_date, effective_end_date)
            for x in range(time_slices)
        ]
        dataset_slices = []
        for feature_slice in feature_slices:
            for forecast_window in forecast_windows:
                label_slice = feature_slice + forecast_window
                dataset_slices.append((feature_slice, label_slice))
        os.makedirs(os.path.dirname(output_slices_path), exist_ok=True)
        with open(output_slices_path, "wb+") as save_path:
            pickle.dump(dataset_slices, save_path)
        return dataset_slices
Esempio n. 5
0
def get_random_visitor(start_date, end_date):
    d = start_date
    random_date = radar.random_date(start=start_date, stop=end_date)
    wh_uri = WH_LOGS_SOURCE + random_date.strftime('%Y-%m-%d') + '.json'
    vistors = None
    try:
        response = requests.get(wh_uri)
        response.raise_for_status()

        # rv = random.sample(response.json(),len(response.json()))
        rv_json = random.choice(response.json())
        if rv_json['place'] != 'White House':
            get_random_visitor(start_date, end_date)
        else:
            # get the date
            rvdate = datetime.datetime.strptime(rv_json['date'], '%Y-%m-%d')
            v_date = rvdate.strftime('%b %d, %Y')
            v = rv_json['visitor']
            vname = v['first_name'] + ' ' + v['last_name']
            title = v['title'] if v['title'] else ''
            org = v['organization']['name'] if v['organization'] else ''

            txt = 'On ' + v_date + ' ' + vname + ' ' + title + ' ' + org + ' visited the White House'
            print txt
            print(len(txt))
            return ' '.join(txt.split())

    except requests.exceptions.HTTPError as err:
        get_random_visitor(start_date, end_date)
Esempio n. 6
0
 def test_02_random_date(self):
     """
     Test ``radar.random_datetime``.
     """
     res = radar.random_date()
     self.assertTrue(isinstance(res, datetime.date))
     return res
Esempio n. 7
0
    def get_random_visitor(self, start_date, end_date):
        d = start_date
        random_date = radar.random_date(start=start_date, stop=end_date)
        wh_uri = WH_LOGS_SOURCE + random_date.strftime('%Y-%m-%d') + '.json'
        vistors = None
        txt = None
        try:
            response = requests.get(wh_uri)
            response.raise_for_status()
            rv_json = random.choice(response.json())
            if rv_json['place'] != 'White House':
                get_random_visitor(start_date, end_date)
            else:
                # get the date
                rvdate = datetime.datetime.strptime(rv_json['date'],
                                                    '%Y-%m-%d')
                v_date = rvdate.strftime('%b %d, %Y')
                v = rv_json['visitor']
                vname = v['first_name'] + ' ' + v['last_name']
                title = v['title'] if v['title'] else ''
                org = v['organization']['name'] if v['organization'] else ''
                txt = '{0} {1} {2} {3} visited the White House'.format(
                    v_date, vname, title, org)

        except requests.exceptions.HTTPError as err:
            get_random_visitor(start_date, end_date)

        return txt
Esempio n. 8
0
    def gen_datetime(self, from_date, to_date):

        from_date = from_date.split('-')

        return radar.random_date(
            start=datetime(year=from_date.year,
                           month=from_date.month, day=from_date.day),
            stop=datetime(year=to_date.year, month=to_date.month, day=to_date.day))
Esempio n. 9
0
def create_config(seed):
    random.seed(seed)
    random.shuffle(amis)
    random.shuffle(household)
    name_laughingmistress(laughingmistress)
    random.shuffle(seamstresses)

    ## pick a random date somewhere between bd and the end of the year
    story_start_time = radar.random_date(start=datetime.datetime(year=1832,
                                                                 month=6,
                                                                 day=7),
                                         stop=datetime.datetime(year=1832,
                                                                month=12,
                                                                day=31))
    if story_start_time.hour < 8:
        story_start_time = story_start_time + timedelta(hours=8)
    if story_start_time.hour > 20:
        story_start_time = story_start_time - timedelta(hours=8)

    ## pick the place where they're walking

    story_start_place = random.choice(Place.listof)

    ## pick a protagonist
    if random.random() < 0.3:
        protagonist = cosette
    else:
        protagonist = amis[0]

    ## pick a confidant
    if protagonist == cosette:
        confidant = random.choice(household)
    elif protagonist == marius:
        confidant = random.choice(household + [courfeyrac])
    elif protagonist == courfeyrac:
        amis.pop(0)
        amis.append(marius)
        random.shuffle(amis)
        amis.insert(0, courfeyrac)
        confidant = amis[1]
    else:
        confidant = amis[1]

    ## pick a garment
    if protagonist.gender == 'F':
        garment = random.choice([x for x in Garment.listof if x.gender == 'F'])
    else:
        garment = random.choice([x for x in Garment.listof if x.gender == 'M'])
    # pick a seamstress
    seamstress = seamstresses[0]

    config = Config(protagonist, confidant, seamstress, story_start_place,
                    story_start_time, garment, amis, household, seamstresses)
    return config
Esempio n. 10
0
    def test_04_random_date_with_ranges_given(self):
        """
        Test ``radar.random_date`` with ranges given.
        """
        start = datetime.date(year=2000, month=5, day=24)
        stop = datetime.date(year=2013, month=5, day=24)

        res = radar.random_date(start=start, stop=stop)
        self.assertTrue(isinstance(res, datetime.date))
        self.assertTrue(res > start)
        self.assertTrue(res < stop)
        return res
Esempio n. 11
0
    def test_04_random_date_with_ranges_given(self):
        """
        Test ``radar.random_date`` with ranges given.
        """
        start = datetime.date(year=2000, month=5, day=24)
        stop = datetime.date(year=2013, month=5, day=24)

        res = radar.random_date(start=start, stop=stop)
        self.assertTrue(isinstance(res, datetime.date))
        self.assertTrue(res > start)
        self.assertTrue(res < stop)
        return res
def insert_prescribe(
    l, emp_ssn1, emp_ssn2, pat_ssn1, pat_ssn2
):  # l - number of prescribes, i:j - available employee ssn, m:m - available patient ssn
    inserts = "INSERT INTO Prescribe (employee_ssn, patient_ssn, description, date) VALUES\n "

    for k in range(l):
        inserts += "({}, {}, '{}', '{}'),\n".format(
            random.randint(emp_ssn1, emp_ssn2 - 1),
            random.randint(pat_ssn1, pat_ssn2 - 1), "Doctor attends patient",
            radar.random_date(start=datetime.date(year=2015, month=5, day=24),
                              stop=datetime.date(year=2019, month=5, day=24)))
    inserts = inserts[:-2] + ';\n'
    return inserts
def insert_analysis_result(i, pat_ssn1, pat_ssn2):
    inserts = "INSERT INTO Analysis_result (id, patient_ssn, type, result, date) VALUES\n "

    for j in range(i):
        inserts += "({}, {}, '{}', '{}', '{}'),\n".format(
            j,
            random.randint(pat_ssn1, pat_ssn2 - 1),
            random.choice(random_data.analysis_types),
            'Medical result',
            radar.random_date(start=datetime.date(year=2015, month=5, day=24),
                              stop=datetime.date(year=2019, month=5, day=24)),
        )
    inserts = inserts[:-2] + ';\n'
    return inserts
def insert_log(i):  # i - number of logs id's
    inserts = "INSERT INTO Log (id, name, description, time) VALUES \n"

    for k in range(i):
        inserts += "({}, '{}', '{}', '{}'),\n".format(
            k, "log_{}".format(k), "initialization",
            radar.random_date(start=datetime.datetime(year=2015,
                                                      month=5,
                                                      day=24),
                              stop=datetime.datetime(year=2019,
                                                     month=5,
                                                     day=24)))

    inserts = inserts[:-2] + ';\n'
    return inserts
Esempio n. 15
0
    def test_06_random_date_with_string_ranges_given(self):
        """
        Test ``radar.random_date`` with string ranges given.
        """
        start = '2012-05-24'
        stop='2013-05-24'

        dt_start = datetime.date(year=2012, month=5, day=24)
        dt_stop = datetime.date(year=2013, month=5, day=24)

        res = radar.random_date(start=start, stop=stop)
        self.assertTrue(isinstance(res, datetime.date))
        self.assertTrue(res > dt_start)
        self.assertTrue(res < dt_stop)
        return res
Esempio n. 16
0
    def test_06_random_date_with_string_ranges_given(self):
        """
        Test ``radar.random_date`` with string ranges given.
        """
        start = '2012-05-24'
        stop = '2013-05-24'

        dt_start = datetime.date(year=2012, month=5, day=24)
        dt_stop = datetime.date(year=2013, month=5, day=24)

        res = radar.random_date(start=start, stop=stop)
        self.assertTrue(isinstance(res, datetime.date))
        self.assertTrue(res > dt_start)
        self.assertTrue(res < dt_stop)
        return res
def insert_patient(
        pat_ssn1, pat_ssn2, room_id1,
        room_id2):  # i:j - available ssn's m:n - available room_id's
    inserts = "INSERT INTO Patient (ssn, name, surname, gender, weight, birth_date, height, blood_type, phone, country, city, street, building, room_id) VALUES \n"
    for k in range(pat_ssn1, pat_ssn2):
        inserts += "({}, '{}', '{}', '{}', {}, '{}', {}, '{}', '+{}', '{}', '{}', '{}', {}, {}),\n".format(
            k, random.choice(random_data.names),
            random.choice(random_data.surnames),
            random.choice(random_data.genders), random.randint(45, 100),
            radar.random_date(start=datetime.date(year=1960, month=5, day=24),
                              stop=datetime.date(year=2013, month=5, day=24)),
            random.randint(80, 220), random.choice(random_data.blood_type),
            random.randint(10**11, 10**12 - 1),
            random.choice(random_data.countries),
            random.choice(random_data.cities),
            random.choice(random_data.street), random.randint(1, 10),
            random.randint(room_id1, room_id2 - 1))

    inserts = inserts[:-2] + ';\n'
    return inserts
    def create_outbreak_source(self):

        #FIXME: USe the antibiogram object helpers!!
        chosen_antibiogram = self.antibiogram.choose_random_antibiogram()

        # FIXME: Caused an issue where a continual loop ran out of options
        # FYI: Could argue that in real life the same strain will occur completley unrelated
        # Remove the antibiogram so that it cannot be used again creating noise
        #self.antibiogram.antibiogram_list.remove(chosen_antibiogram)

        chosen_individual = self.choose_suitable_individual()

        chosen_individual_id = chosen_individual.id
        # Randomly choose a location to start the outbreak
        chosen_location = random.choice(chosen_individual.location_list)

        # Pick a date to start the outbreak
        date_of_infection = radar.random_date(
            start=chosen_location.admission_date,
            stop=chosen_location.discharge_date,
        )

        self.outbreak_source = {
            'antibiogram': chosen_antibiogram,
            'individual': chosen_individual,
            'location': chosen_location,
            'date_of_infection': date_of_infection,
            'level': 1
        }

        self.writer.writerow({
            'source_individual': "",
            'individual': chosen_individual_id,
            'location': chosen_location.name,
            'date_of_infection': date_of_infection,
            'level': 1
        })

        self.isolate_start_id += 1

        self.add_isolate(self.isolate_start_id, chosen_individual_id, date_of_infection)
    def generate(self):
        evictions = []
        if not os.path.isfile("addresses.db"):
            raise FileNotFoundError("Did you generate the sqlite database yet?")
        connection = sqlite3.connect("addresses.db")
        c = connection.cursor()
        sql_to_execute = 'SELECT * FROM address ORDER BY RANDOM() LIMIT {}'.format(self.params["number_to_generate"])
        rows = c.execute(sql_to_execute).fetchall()
        connection.close()

        for row in rows:
            evictions.append({ key: val for key, val in zip(self.headers, row) })

        for eviction in evictions:
            eviction["date"] = str(radar.random_date(
                    start = self.params["start_date"],
                    stop = self.params["end_date"]
                    ))
        evictions.sort(key = lambda d: d["date"])

        return evictions
def insert_treatment_plan(n, doc_ssn1, doc_snn_2, pat_snn1, pat_snn_2):
    ans = ""
    ids = list(range(0, n))
    random.shuffle(ids)
    doc_snn = []
    for j in range(n):
        doc_snn.append(random.randint(doc_ssn1, doc_snn_2 - 1))

    pat_snn = []
    for j in range(n):
        pat_snn.append(random.randint(pat_snn1, pat_snn_2 - 1))

    two_weeks = 1209600
    treats = list(open("Treatments.txt"))
    for i in range(len(treats)):
        treats[i] = treats[i].replace("\n", "")

    while treats.count(""):
        treats.remove("")

    string = ""
    for i, pro in enumerate(treats):
        string += "({}, '{}'),\n".format(i, pro.split(";")[0])
    ans += "INSERT INTO Diagnoses VALUES \n" + string[:-2] + ";\n\n"

    c = 0
    string = ""
    thing = {}
    opthing = {}
    for i, pro in enumerate(treats):
        a = []
        for e2 in pro.split(";")[1:]:
            if (not (e2 in opthing)):
                string += "({}, '{}'),\n".format(c, e2)
                a.append(c)
                opthing[e2] = c
                c += 1
            else:
                a.append(opthing[e2])
        thing[i] = a

    ans += "INSERT INTO Procedures VALUES \n" + string[:-2] + ";\n\n"

    string1 = ""
    string2 = ""
    string3 = ""
    for i in range(n):
        hos_date = radar.random_date(start=datetime.date(year=2015,
                                                         month=1,
                                                         day=1),
                                     stop=datetime.date(year=2019,
                                                        month=1,
                                                        day=1))
        timestamp = datetime.datetime.combine(hos_date,
                                              datetime.time(0, 0)).timestamp()
        dis_date = datetime.date.fromtimestamp(timestamp + two_weeks)
        string1 += "({}, {}, {}, '{}', '{}'),\n".format(
            ids[i], doc_snn[i], pat_snn[i], dis_date, hos_date)
        illness = random.sample(range(len(treats)), 3)
        for e in illness:
            string2 += "({}, {}),\n".format(ids[i], e)
            string3 += "({}, {}),\n".format(ids[i], random.choice(thing[e]))

    ans += "INSERT INTO Treatment_plan VALUES\n" + string1[:-2] + ";\n\n"
    ans += "INSERT INTO Treatment_diagnoses  VALUES\n" + string2[:-2] + ";\n\n"
    ans += "INSERT INTO Treatment_procedures VALUES\n" + string3[:-2] + ";\n\n"
    return ans
Esempio n. 21
0
        recordValue[13] = initial  #n
        recordValue[14] = firstName  #o
        recordValue[15] = COL_P  #p
        recordValue[16] = lastName  #q
        recordValue[17] = street  #r
        recordValue[18] = apt  #s
        recordValue[19] = COL_T  #t
        recordValue[20] = city  #u
        recordValue[21] = state  #v
        recordValue[22] = zipcode  #w
        recordValue[23] = COL_X  #x
        recordValue[24] = COL_Y[0]  #y Residency Code - U

        dob = radar.random_date(start=datetime.date(year=startDobYear,
                                                    month=1,
                                                    day=1),
                                stop=datetime.date(year=endDobYear,
                                                   month=12,
                                                   day=30))

        recordValue[25] = dateFormat(dob)  #z

        recordValue[26] = random.choice(COL_AA)  #aa
        recordValue[27] = random.choice(COL_AB)  #ab
        recordValue[28] = COL_AC  #ac
        recordValue[29] = COL_AD  #ad
        recordValue[30] = COL_AE  #ae
        recordValue[31] = COL_AF  #af
        recordValue[32] = COL_AG  #ag
        recordValue[33] = COL_AH  #ah
        recordValue[34] = email  #ai
        recordValue[35] = COL_AJ  #aj
Esempio n. 22
0
def generate_date_of_birth():
    return radar.random_date(
        start = datetime.date(1971,1,1),
        stop = Zombie.DATE_OF_OUTBREAK - datetime.timedelta(weeks=11*52)
    )
Esempio n. 23
0
def generate_date_of_rebirth():
    return radar.random_date(
        start = Zombie.DATE_OF_OUTBREAK,
        stop = datetime.date.today()
    )
Esempio n. 24
0
 def gen_datetime(self):
     return radar.random_date(
         start=datetime(year=2018, month=1, day=1),
         stop=datetime(year=2019, month=10, day=26))
Esempio n. 25
0
def Populate(N=5):
    for _ in range(N):

        fake_cmtsNombre = choice([
            'VILLA EL SALVADOR1', 'SAN JUAN4', '1EROMAYO1', 'CHORRILLOS1',
            'MAGDALENA2', 'MAGDALENA1', 'SAN JUAN1', 'SAN JUAN2', 'SAN JUAN3'
        ])
        fake_nodoNombre = choice([
            'CA', 'CU', 'CV', 'LC', 'LF', 'LM', 'LO', 'MA', 'MI', 'P3', 'PI',
            'RA', 'RO', 'SB', 'SI', 'SV', 'T1', 'VI', 'WA'
        ])
        fake_trobaNombre = 'R' + str(randrange(100, 105))
        fake_nombre = choice([
            'Jhon', 'Sansa', 'Tyron', 'Aria', 'Brie', 'Bran', 'Ned', 'Rob',
            'Robet', 'Summer', 'Ghost', 'Lady', 'Cathelyn'
        ])
        fake_apellido = choice([
            'Dominguez', 'Lu', 'Ra', 'Zen', 'Brian', 'Tarth', 'Snow', 'Sand',
            'Targaryen', 'Stark', 'Lannister', 'Black Fire'
        ])
        fake_codigoCliente = randrange(100000, 9999999)
        fake_remedy = 'CRQ0000' + str(randrange(393881, 399999))
        fake_estado = choice(['Cerrado', 'Abierto'])
        fake_corteS_N = choice(['True', 'False'])
        fake_tipoTrabajo = choice([
            "PARTICION_OPTICA", "ACONDICIONAR_FUENTE_DE_ENERGIA",
            "CONEXIONADO_DE_DISPOSITIVOS", "PARTICION_COAXIAL", "CONEXIONADO",
            "CAMBIO_DE_TROBA", "TRABAJO_DE_EMERGENCIA"
        ])
        fake_remitente = choice([
            'Jhon', 'Sansa', 'Tyron', 'Aria', 'Brie', 'Bran', 'Ned', 'Rob',
            'Robet', 'Summer', 'Ghost', 'Lady', 'Cathelyn'
        ])
        fake_grupoCoordinador = choice([
            'Busqueda y saneamiento', 'Capacidad y procesos', 'Energia',
            'Huaweia', 'Ingenieria Core IP', 'Ingenieria de Datos',
            'Ingenieria Facilities', 'metro y Backhaul', 'Transporte'
        ])
        fake_riesgo = choice(['1', '2', '3', '4', '5'])
        fake_site = choice([
            'San Borja', 'Carhuacoto', 'La Victoria', 'Lince', 'Cedros',
            'Urubamba', 'Huancas', 'Tuman_Ura', 'San Juan', 'Higuereta'
        ])
        fake_fechaInicio = radar.random_date(start='2019-02-05',
                                             stop='2019-02-12')
        fake_fechaFin = radar.random_date(start='2019-03-10',
                                          stop='2019-05-18')

        cmts1 = Cmts.objects.get_or_create(cmtsNombre=fake_cmtsNombre)[0]
        nodo1 = Nodo.objects.get_or_create(nodoNombre=fake_nodoNombre,
                                           cmts=cmts1)[0]
        troba1 = Troba.objects.get_or_create(trobaNombre=fake_trobaNombre,
                                             nodo=nodo1)[0]
        infoPlanta1 = InfoPlanta.objects.get_or_create(
            remedy=fake_remedy,
            estado=fake_estado,
            corteS_N=fake_corteS_N,
            tipoTrabajo=fake_tipoTrabajo,
            troba=troba1)[0]
        infoCore1 = InfoCore.objects.get_or_create(
            remedy=fake_remedy,
            remitente=fake_remitente,
            grupoCoordinador=fake_grupoCoordinador,
            riesgo=fake_riesgo,
            site=fake_site,
            cmts=cmts1)[0]
        tareaProgramada = TareaProgramada.objects.get_or_create(
            fechaInicio=fake_fechaInicio,
            fechaFin=fake_fechaFin,
            infoCore=infoCore1,
            infoPlanta=infoPlanta1)
        usuario = Usuario.objects.get_or_create(
            nombre=fake_nombre,
            apellido=fake_apellido,
            codigoCliente=fake_codigoCliente,
            troba=troba1)
Esempio n. 26
0
#!/usr/bin/env python3
# -*- coding: utf-8  -*-

import radar
import datetime

print('随机日期 %s' % radar.random_date())

print('随机日期+时间 %s' % radar.random_datetime())

print('随机时间 %s' % radar.random_time())

print('指定范围随机日期 %s' %
      radar.random_date(start=datetime.datetime(year=1985, month=1, day=1),
                        stop=datetime.datetime(year=1989, month=12, day=30)))

print(
    '指定范围随机日期+时间 %s' %
    radar.random_datetime(start=datetime.datetime(year=1985, month=1, day=1),
                          stop=datetime.datetime(year=1989, month=12, day=30)))

print('指定范围随机时间 %s' % radar.random_time(
    start="2018-01-10T09:00:10",
    stop="2018-01-10T18:00:00",
))

# 默认使用 重量级的python-dateutil库解析日期,选择使用轻量级的radar.utils.parse(快5倍)
print('指定范围随机时间 %s' % radar.random_time(start="2018-01-10T09:00:10",
                                        stop="2018-01-10T18:00:00",
                                        parse=radar.utils.parse))
Esempio n. 27
0
def generate_trans_date(count, start, end):
    dates = []
    for i in range(count):
        date = radar.random_date(start=start, stop=end)
        dates.append(date)
    return dates
    def initiate_outbreak_phase(self, previous_phase_output):

        current_phase_output = []
        outbreak_results = []
        outbreak_in_progress = True

        level = self.outbreak_source.get('level')

        while outbreak_in_progress:

            # Increment the phase level
            level += 1

            for source in previous_phase_output:

                source_individual_id = source.get('individual').id

                # Check to see if this individual has already been a source of infection
                if source_individual_id in self.infected_individuals:
                    continue

                print("New source %s" % source_individual_id)

                # Record the source so that they cannot be re-infected
                self.infected_individuals.append(source_individual_id)

                # get all individuals who have shared the locations at the same time
                for individual in self.movement.individual_list:

                    current_individual_id = individual.id

                    # Check if the individual has already been infected (different to the source check!!)
                    uptodate_outbreak_list = outbreak_results + current_phase_output
                    if self.individual_already_part_of_outbreak(source_individual_id, current_individual_id, uptodate_outbreak_list):
                        continue

                    overlapping_location = self.individual_overlap_location(source, individual)

                    if overlapping_location and self.transmission_occured():

                        overlap_location_name = overlapping_location.get('overlap_location_name')
                        overlap_start = overlapping_location.get('overlap_start')
                        overlap_end = overlapping_location.get('overlap_end')

                        # Pick a date to simulate a transmission
                        date_of_transmission = radar.random_date(
                            start=overlap_start,
                            stop=overlap_end,
                        )

                        # Pick a date within the overlap to create a sample date, this would be ideal to know but not
                        # realistic in the real world, the date would be after.
                        # TODO: Define a metric of delay between the date of transmission vs sample

                        current_phase_output.append({
                            'source_individual': source_individual_id,
                            'individual': individual,  # Individual object
                            'location': overlap_location_name,
                            'date_of_infection': date_of_transmission,
                            'overlap_start': overlap_start,
                            'overlap_end': overlap_end,
                        })

                        self.writer.writerow({
                            'source_individual': source_individual_id,
                            'individual': current_individual_id,
                            'location': overlap_location_name,
                            'date_of_infection': date_of_transmission,
                            'level': level
                        })

                        self.stats.add_isolate()

                        # Generate an isolate id
                        isolate_id = self.isolate_start_id + len(self.master_isolate_list)

                        self.add_isolate(isolate_id, current_individual_id, date_of_transmission)

            # if the outbreak has finished
            if not current_phase_output:
                outbreak_in_progress = False
            else:
                # store the result
                outbreak_results = outbreak_results + current_phase_output

            # Set the next phase for another pass if required
            previous_phase_output = current_phase_output
            # Initialise current as empty
            current_phase_output = []

        return outbreak_results
Esempio n. 29
0
from __future__ import print_function

from dateutil.parser import parse as dateuitil_parser
import radar

print(radar.random_date(start='2013-05-24', stop='2013-07-01', parse=dateuitil_parser))

print(radar.random_datetime(start='2013-05-24T00:00:00', stop='2013-05-24T23:59:59', parse=radar.utils.parse))

start = radar.utils.parse('2012-01-01')

stop = radar.utils.parse('2013-01-01')

print(radar.random_datetime(start=start, stop=stop))

print(radar.random_datetime(start=start))

print(radar.random_datetime(stop=stop))

print(radar.random_time(start='2012-01-01T00:00:00', stop='2012-01-01T23:59:59'))
Esempio n. 30
0
# coding=utf-8

import radar

random_date = radar.random_date(start='2017-02-05', stop='2017-05-05')
Esempio n. 31
0
def get_random_date(min, max):
    return radar.random_date(start=min, stop=max)