Beispiel #1
0
    def GET(self, oid, tahun=None, bulan=None, tgl=None):
        try:
            bd = Agent.get(oid)
            if bd.AgentType != 3:
                raise web.notfound(404)
        except:
            raise web.notfound(404)
        if not tgl:
            try:
                tanggal = datetime.date(int(tahun), int(bulan), 1)
                return self.tma_monthly(oid, tahun, bulan)
            except:
                pass
        try:
            tanggal = datetime.date(int(tahun), int(bulan), int(tgl))
        except:
            tanggal = datetime.date.today()
        sebelum = tanggal - datetime.timedelta(days=1)
        sesudah = tanggal + datetime.timedelta(days=1)
        # '#248F8F', '#70DBDB', '#EBFAFA'
        try:
            bendungan = Agent.get(int(oid))
            if bendungan.AgentType != 3:
                raise SQLObjectNotFound
        except SQLObjectNotFound:
            return web.notfound(404)
        plotlines = ""
        tma = bendungan.get_segmented_tma_bendungan()
        series = [float(d[0]) for d in tma.get('kapasitas_series')]
        if tma.get('elevasi'):
            plotlines = "{ value: " + str(tma.get('elevasi') or 0) + "\
                , color: '#cc0000', width: 4, label: {text: '+'"

            +str(tma.get('elevasi') or 0) + "} }, "
        '''
            val_min = min(series, key=lambda x: abs(x - elevasi))
            idx = series.index(val_min)
            series.insert(idx + 1, {'y': elevasi,
                                    'dataLabels': {
                                        'enabled': 'true',
                                        'style': {'fontSize': 24}
                                    },
                          'marker':
                                    {'fillColor': '#33CC33', 'radius': 5}})
'''
        return render_anon.bendungan.show(
            bendungan,
            meta={
                'now': tanggal.strftime('%d %b %y'),
                'before': sebelum.strftime('%d %b %y'),
                'after': sesudah.strftime('%d %b %y'),
                'categories1':
                [float(d[1]) for d in tma.get('kapasitas_series')],
                'categories': [],
                'series': series,
                'plotlines': plotlines,
                'tma': tma
            })
Beispiel #2
0
 def GET(self, pid):
     try:
         oid = Agent.select(Agent.q.prima_id == pid)[0].AgentId
         bd = Agent.get(oid)
         if bd.AgentType != 3:
             raise web.notfound(404)
     except:
         raise web.notfound(404)
     tanggal = web.input().get('d')
     if not tanggal:
         tanggal = datetime.date.today()
     else:
         tanggal = to_date(tanggal)
     try:
         bendungan = Agent.get(int(oid))
         if bendungan.AgentType != 3:
             raise SQLObjectNotFound
     except SQLObjectNotFound:
         return web.notfound(404)
     sql = "SELECT SamplingDate, SamplingTime, WLevel, Temperature, Humidity, Rain4 FROM %(table_name)s \
             ORDER BY SamplingDate DESC, SamplingTime DESC \
             LIMIT 0, 25" % ({
         'table_name': bendungan.table_name
     })
     rst = [(int(r[0].strftime('%s')) + r[1].seconds, r[2], r[3], r[4],
             r[5]) for r in bendungan._connection.queryAll(sql)]
     latest = {}
     if not rst:
         sql = "SELECT SamplingDate, SamplingTime, WLevel, Temperature, Humidity, Rain4 FROM %(table_name)s \
             ORDER BY SamplingDate, SamplingTime LIMIT 0, 25" % ({
             'table_name':
             bendungan.table_name
         })
         rst = [(int(r[0].strftime('%s')) + r[1].seconds, r[2], r[3], r[4],
                 r[5]) for r in bendungan._connection.queryAll(sql)]
     d = rst[0]
     samp = datetime.datetime.fromtimestamp(d[0])
     if samp.date() == datetime.date.today():
         sampling = samp.strftime('%H:%M')
     else:
         sampling = samp.strftime('%d %b %H:%M')
     latest = dict(sampling=sampling,
                   wlevel=d[1] / 100.0,
                   temperature=d[2],
                   humidity=d[3],
                   sq=d[4])
     return render.bendungan.liveprima(bendungan,
                                       meta={
                                           'now':
                                           tanggal.strftime('%d %b %y'),
                                           'tma': rst,
                                           'latest_sampling': latest
                                       })
Beispiel #3
0
 def GET(self, oid):
     bendung = Agent.get(int(oid))
     meta = {
         "dari": datetime.date(2017, 1, 1),
         "hingga": datetime.date(2017, 3, 1)
     }
     return render.bendungan.keamanan.index(bendung, meta)
Beispiel #4
0
    def GET(self, pid):
        try:
            pos = Agent.get(pid)
        except SQLObjectNotFound:
            return web.notfound()
        try:
            dari = to_date(web.input().dari)
            dari = datetime.datetime.combine(dari, datetime.time(7, 0, 0))
            hingga = to_date(web.input().hingga)
            hingga = datetime.datetime.combine(hingga,
                                               datetime.datetime.now().time())
        except:
            hingga = datetime.datetime.now()
            dari = hingga - datetime.timedelta(days=2)
            dari = dari.replace(hour=7, minute=0, second=0)
        #print dari, hingga
        tma_trend = pos.get_log_tma(dari, hingga)

        series = [
            '{x: %s, y: %s}' %
            (int(a[0].strftime('%s')) + a[1].seconds, float(a[2] or 0) * 0.01)
            for a in tma_trend
        ]
        data_series = [{
            'nama': pos.cname,
            'series': ', '.join(series),
            'satuan': 'M'
        }]

        return render.bendungan.show_tma({
            'pos': pos,
            'data': data_series,
            'dari': dari,
            'hingga': hingga
        })
Beispiel #5
0
    def GET(self):
        #return "development test"
        tanggal = web.input().get('d')
        if not tanggal:
            tanggal = datetime.date.today()
        else:
            try:
                tanggal = datetime.datetime.strptime(tanggal,
                                                     "%Y-%m-%d").date()
            except:
                tanggal = datetime.datetime.strptime(tanggal,
                                                     "%d %b %y").date()
        HIDE_THIS = [
            a.strip() for a in open('HIDE_AWLR.txt').read().split(',')
        ]
        agents = Agent.select(
            AND(OR(Agent.q.AgentType == HIDROLOGI, Agent.q.AgentType == 0),
                Agent.q.expose == True)).orderBy(["wilayah", "urutan"])
        agents = [a for a in agents if a.table_name not in HIDE_THIS]
        data = [
            Struct(**{
                'pos': a,
                'tma': Struct(**a.get_segmented_wl(tanggal))
            }) for a in agents
        ]
        js = """
        <script type="text/javascript">
        $(function(){
            $('.tanggal').datepicker({dateFormat: 'd M y'});
            $('.show-current-date').bind('change', function () {
             $(this).parent().submit()});
        });
        </script>"""
        sebelum = tanggal - datetime.timedelta(days=1)
        sesudah = tanggal + datetime.timedelta(days=1)

        # water level tertinggi
        sql = "SELECT MAX(pagi), agent_id, waktu FROM tma"
        res = Agent._connection.queryAll(sql)
        if res:
            try:
                (total, agent_id, waktu) = res[0]
                tertinggi = Struct(**{
                    'agent': Agent.get(agent_id),
                    'total': total,
                    'waktu': waktu
                })
            except IndexError:
                tertinggi = Struct()

        return render.tma.tma_diff(tma=data,
                                   meta={
                                       'now': tanggal.strftime('%d %b %y'),
                                       'before': sebelum.strftime('%d %b %y'),
                                       'after': sesudah.strftime('%d %b %y'),
                                       'tertinggi': tertinggi
                                   },
                                   wilayah=WILAYAH,
                                   js=js)
Beispiel #6
0
    def GET(self, oid):
        try:
            bendung = Agent.get(int(oid))
        except SQLObjectNotFound:
            return web.notfound()
        inp = web.input()
        if inp.get('periode'):
            periode = to_date(inp.periode)
        else:
            periode = datetime.date.today()
        if periode.month < 11:
            periode = datetime.date(periode.year - 1, 11,
                                    1)  # 1 Nop tahun lalu
        else:
            periode = datetime.date(periode.year, 11, 1)

        tanggal = periode
        if periode.month > 10:
            tanggal = datetime.date(tanggal.year + 1, 11, 1)

        if tanggal.year <= 2018:
            jhar = [30, 31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31]
            rr = []
            for i in range(12):
                rr.append(periode.replace(day=1))
                rr.append(periode.replace(day=16))
                periode += datetime.timedelta(days=jhar[i])
        if tanggal.year > 2018:
            jhar = [30, 31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31]
            rr = []
            for i in range(12):
                rr.append(periode.replace(day=15))
                rr.append(periode.replace(day=jhar[i]))
                periode += datetime.timedelta(days=jhar[i])
        sql = "SELECT waktu, po_tma, po_inflow_q, po_inflow_v, \
                po_outflow_q, po_outflow_v, \
                tma6, vol6, inflow_q, inflow_v, intake_q, intake_v, po_bona, po_bonb, vol_bona, vol_bonb \
                FROM waduk_daily \
                WHERE waktu IN (%s) AND pos_id=%s \
                ORDER BY waktu" % (','.join(["'" + str(i) + "'"
                                             for i in rr]), oid)
        rst = Agent._connection.queryAll(sql)
        sql_realisasi = "SELECT \
                tma6, vol6, inflow_q, inflow_v, intake_q, intake_v \
                FROM waduk_daily \
                WHERE pos_id=%s AND waktu BETWEEN %s AND %s \
                ORDER BY waktu"

        meta = {
            'rst': rst,
            'daily': [],
            'dari': periode,
            'hingga': periode,
            'tanggal': tanggal
        }
        return render.bendungan.operasi(bendung, meta)
Beispiel #7
0
 def GET(self):
     try:
         tanggal = to_date(web.input().get('d'))
     except:
         tanggal = datetime.date.today()
     poses = dict([l.split('\t') for l in open(
         'agent_table.txt').readlines()])
     agent_klimatologi = [Agent.get(poses.get(a)) for a in KLIMATOLOGI_POS]
     agent_klimatologi = [(a, a.get_segmented_klimatologi(tanggal)) for a in agent_klimatologi]
     return render.klimatologi.index({'pos': agent_klimatologi, 'tanggal': tanggal, 'sebelum': tanggal - datetime.timedelta(days=1), 'sesudah': tanggal + datetime.timedelta(days=1)})
Beispiel #8
0
 def GET(self, table_name):
     '''Masuk ke sini jika authuser.is_admin == 4'''
     agent_id = dict([a.split('\t') for a in open('agent_table.txt').readlines()]).get(table_name)
     pos = Agent.get(agent_id)
     webinput = web.input(sampling=str(datetime.date.today() - datetime.timedelta(days=1)))
     tg = datetime.datetime.strptime(webinput.sampling, '%Y-%m-%d').date()
     rst = KlimatManual.select(AND(func.YEAR(KlimatManual.q.sampling)==tg.year, 
         func.MONTH(KlimatManual.q.sampling)==tg.month, KlimatManual.q.agent==agent_id))
         
     return render.adm.klimatologi.show({'tg': tg, 'pos': pos, 'data': rst})
Beispiel #9
0
 def GET(self, pid):
     try:
         pos = Agent.get(pid)
     except SQLObjectNotFound:
         return web.notfound()
     hingga = datetime.datetime.now()
     dari = hingga - datetime.timedelta(days=3)
     tma_trend = pos.get_log_tma(dari, hingga)
     series = [(str(a[0]), str(a[1]), float(a[2] or 0) * 0.01)
               for a in tma_trend]
     return render.tma.show({'pos': pos, 'data': series})
Beispiel #10
0
 def GET(self, loc):
     agents = dict([(r.table_name, r.AgentId) for r in Agent.select(OR(Agent.q.AgentType==3, Agent.q.AgentType==2))])
     if agents.get(loc):
         sql = "SELECT SamplingDate, SamplingTime, WLevel/100.0 FROM %s \
             ORDER BY SamplingDate DESC, SamplingTime DESC \
             LIMIT 0, 1" % loc
         rst = conn.queryAll(sql)
         if rst:
             pos = Agent.get(agents.get(loc))
             sampling = datetime.datetime.fromtimestamp(int(rst[0][0].strftime('%s')) + rst[0][1].seconds)
             web.header('Content-Type', 'text/plain')
             web.header('Access-Control-Allow-Origin', '*')
             return pos.cname + '|' + sampling.strftime('%d%b%y|%H:%M') + '|' + 'TMA: %.2f' % (pos.DPL + float(rst[0][2] or 0))
     return web.notfound()
Beispiel #11
0
 def GET(self, oid):
     try:
         bendung = Agent.get(int(oid))
     except SQLObjectNotFound:
         return web.notfound()
     dari = datetime.date(2017, 3, 1)
     hingga = datetime.date(2017, 3, 31)
     meta = {
         "dari":
         dari,
         "hingga":
         hingga,
         "daily":
         WadukDaily.select(
             AND(WadukDaily.q.pos == bendung, WadukDaily.q.waktu >= dari,
                 WadukDaily.q.waktu <= hingga))
     }
     return render.bendungan.pemantauan(bendung, meta)
Beispiel #12
0
    def GET(self):
        try:
            tanggal = to_date(web.input().get('d'))
        except:
            tanggal = datetime.date.today()
        AGENT_TABLE = dict([
            a.strip().split('\t') for a in open('agent_table.txt').readlines()
        ])
        poses = []
        db = Agent._connection
        for a in DEBIT_POS.keys():
            pos = Agent.get(int(AGENT_TABLE.get(a)))
            if pos.lengkung_kapasitas:
                pos.lengkung_series = [
                    map(float,
                        s.strip().split('\t'))
                    for s in pos.lengkung_kapasitas.split('\n')
                ]
            formula = DEBIT_POS.get(a)
            if formula:
                pos.debit_formula = formula
            sql = "SELECT CONCAT(SamplingDate, ' ', SamplingTime), WLevel*0.01 AS WLevel FROM %s ORDER BY SamplingDate DESC, SamplingTime DESC LIMIT 0, 1" % (
                a, )
            rst = db.queryAll(sql)
            try:
                tma = float(rst[0][1])
                pos.tma = {
                    'tanggal':
                    datetime.datetime.strptime(rst[0][0], '%Y-%m-%d %H:%M:%S'),
                    'tma':
                    tma
                }
                debit = formula.get('a') * (tma -
                                            formula.get('b'))**formula.get('c')
                pos.debit = debit
            except:
                pos.tma = {'tanggal': None, 'tma': None}
                pos.debit = None

            poses.append(pos)

        return render.tma.lengkung_debit({'poses': poses, 'tanggal': tanggal})
Beispiel #13
0
    def GET(self):
        id_tma = (204, 2, 12, 47, 5, 6, 41, 54, 240, 45)
        today = datetime.date.today()
        lalu = today - datetime.timedelta(days=(today.day + 59))
        lalu = lalu.replace(day=1)
        h = lalu
        haris = {}
        while (h < today):
            h += datetime.timedelta(days=1)
            haris[int(h.strftime("%s")) * 1000] = 0
        hujan = PeriodikJam.select(
            AND(PeriodikJam.q.rain > 0, PeriodikJam.q.sampling > lalu))
        hujan_terjadi = {}
        for h in hujan:
            try:
                haris[int(h.sampling.date().strftime('%s')) * 1000] += h.rain
            except KeyError:
                pass
            '''
            pos_id = h.agent.AgentId

            if pos_id not in hh:
                hh[pos_id] = h.rain
            else:
                hh[pos_id] += h.rain
            '''
        pos_tma = []
        for i in id_tma:
            try:
                a = Agent.get(i)
                pos_tma.append((a, a.get_tma()))
            except:
                pass

        return render_plain.index({
            'hujan': hujan,
            'series': haris,
            'pos_tma': pos_tma,
            'wilayah': WILAYAH
        })
Beispiel #14
0
    def GET(self, bd):
        '''Tampilkan data Piezometer untuk lokasi "bd"
        Default tampilkan data terakhir, kecuali ada sampling yang diinginkan
        Menampilkan data selama _bulan_terpilih_
        '''
        inp = web.input()
        sampling = inp.get('sampling', None)
        bendungans = dict(
            [a.strip().split() for a in open('agent_table.txt').readlines()])
        id_bdg = bendungans.get(bd)
        if not id_bdg:
            return web.notfound()
        sql = "SELECT MAX(waktu) FROM waduk_daily WHERE pos_id=%s" % id_bdg
        rst = Agent._connection.queryAll(sql)
        if not sampling:
            sampling = rst[0]

        sampling = sampling and to_date(sampling) or None

        pos = Agent.get(id_bdg)

        if sampling.month == datetime.date.today().month:
            wds = [
                wd for wd in WadukDaily.select(
                    WadukDaily.q.pos == pos).orderBy('-waktu')
                if wd.waktu.year == sampling.year
                and wd.waktu.month == sampling.month
            ]
        else:
            wds = [
                wd for wd in WadukDaily.select(WadukDaily.q.pos == pos)
                if wd.waktu.year == sampling.year and wd.waktu.month ==
                sampling.month and wd.waktu.day <= datetime.date.today().day
            ]

        return render.bendungan.piezometer({
            'pos': pos,
            'bulan': sampling,
            'wds': wds
        })
Beispiel #15
0
    def POST(self, table_name):
        agent_id = dict([a.split('\t') for a in open('agent_table.txt').readlines()]).get(table_name)
        pos = Agent.get(agent_id)
        try:
            pos = [a for a in AgentCh.select(AgentCh.q.AgentType==1) if a.table_name == table_name][0]
        except IndexError:
            return web.notfound()
        inp = web.input()
        float_list = 'ch_m,temp_min_m,temp_max_m,humi_m,kec_angin_m,penguapan_m'.split(',')
        for kol in float_list:
            if inp.get(kol):
                inp.update({kol: float(inp.get(kol))})
            else:
                inp.update({kol: None})

        inp.update({'penyinaran_m': inp.get('penyinaran_m') and int(inp.get('penyinaran_m')) or None})
        inp.update({'agentID': pos.id, 'cuser': session.username, 'cdate': datetime.datetime.now()})
        inp.update({'sampling': to_date(inp.get('sampling'))})
        if 'csrf_token' in inp:
            del inp['csrf_token']
        rst = KlimatManual.select(AND(KlimatManual.q.agent==pos, 
                func.DATE(KlimatManual.q.sampling)==inp.get('sampling')))
        if rst.count():
            rst[0].set(**inp)
        else:
            km = KlimatManual(**inp)

        # table curahhujan perlu ditambah/update
        ch = CurahHujan.select(AND(CurahHujan.q.agent==pos,
            func.DATE(CurahHujan.q.waktu) == inp.get('sampling')))
        if ch.count():
            ch[0].set(**{'manual': float(inp.get('ch_m', 0))})
        else:
            ch = CurahHujan(**{'waktu': inp.get('sampling'), 
                'manual': float(inp.get('ch_m', 0)), 'agent': pos})
        return web.redirect('/adm/klimatologi/' + table_name, absolute=True)
Beispiel #16
0
 def GET(self, oid):
     try:
         bd = Agent.get(oid)
         if bd.AgentType != 3:
             raise web.notfound(404)
     except:
         raise web.notfound(404)
     tanggal = web.input().get('d')
     if not tanggal:
         tanggal = datetime.date.today()
     else:
         tanggal = to_date(tanggal)
     sebelum = tanggal - datetime.timedelta(days=1)
     sesudah = tanggal + datetime.timedelta(days=1)
     try:
         bendungan = Agent.get(int(oid))
         if bendungan.AgentType != 3:
             raise SQLObjectNotFound
     except SQLObjectNotFound:
         return web.notfound(404)
     s_mamin = 5.8
     s_mabanjir = 10.8
     plotlines = ""
     tma = bendungan.get_segmented_tma_bendungan(tanggal)
     series = [[float(v), float(k)] for k, v in tma.get('kapasitas_series')]
     elev_series = []
     if tma.get('elevasi'):
         s_elevasi = (s_mabanjir -
                      s_mamin) / (bendungan.siaga3 - bendungan.siaga4) * (
                          tma.get('elevasi') - bendungan.siaga4) + s_mamin
         plotlines = "{ value: \
             "                  + str(s_elevasi) + "\
             , color: '#000099', width: 2, label: {text: '+"\
             + str(tma.get('elevasi') or 0) + "', style: {fontSize: 24, backgroundColor: 'white'}}}, "
         elev_series = [[e[0], tma.get('elevasi') or 0] for e in series]
     return render.bendungan.elevasi(
         bendungan,
         meta={
             'now':
             tanggal.strftime('%d %b %y'),
             'before':
             sebelum.strftime('%d %b %y'),
             'after':
             sesudah.strftime('%d %b %y'),
             'categories1':
             [float(d[1]) for d in tma.get('kapasitas_series')],
             's_ma_min':
             s_mamin,
             's_ma_normal': (s_mabanjir - s_mamin) /
             (bendungan.siaga3 - bendungan.siaga4) *
             (bendungan.siaga1 - bendungan.siaga4) + s_mamin,
             's_ma_banjir':
             s_mabanjir,
             'series':
             series,
             'elev_series':
             elev_series,
             'plotlines':
             plotlines,
             'tma':
             tma
         })
Beispiel #17
0
    def GET(self, pid):
        try:
            pos = Agent.get(pid)
        except SQLObjectNotFound:
            return web.notfound()
        pics = []
        if pos.table_name in CCTV_POS:
            # mendapatkan 3 nama file terakhir dari CCTV FTP Server
            try:
                ftp = FTP(FTP_HOST)
                ftp.login()
                ftp.cwd(CCTV_IMG_DIR + '/' + pos.table_name)
                nlst = ftp.nlst()
                pics = nlst[-3:]
            except:
                pics = [
                    'Fail to Connect CCTV Server',
                    'Fail to Connect CCTV Server',
                    'Fail to Connect CCTV Server'
                ]
        try:
            dari = to_date(web.input().dari)
            dari = datetime.datetime.combine(dari, datetime.time(7, 0, 0))
            hingga = to_date(web.input().hingga)
            hingga = datetime.datetime.combine(hingga,
                                               datetime.datetime.now().time())
        except:
            hingga = datetime.datetime.now()
            dari = hingga - datetime.timedelta(days=3)
            dari = dari.replace(hour=7, minute=0, second=0)

        tma_trend = pos.get_log_tma(dari, hingga)

        # membuat pola waktu per jam
        ch_patt = []
        t = int(dari.strftime('%s'))
        thingga = int(hingga.strftime('%s'))
        while t <= thingga:
            ch_patt.append([t, 0])
            t += 60 * 60  # 60 * 60 = 60 menit/1 jam
        ch_patt = dict(ch_patt)
        series = [[a[0], a[1], float(a[2] or 0) * 0.01] for a in tma_trend]
        print len(ch_patt), len(series)
        data_series = [{'nama': pos.cname, 'series': series, 'satuan': 'M'}]
        # menghitung Debit
        if pos.table_name in DEBIT_POS.keys():
            formula = DEBIT_POS.get(pos.table_name)
            if formula:
                series = []  # series of debit
                for tgl, jam, tma in data_series[0].get('series'):
                    tma_lokal = tma - pos.DPL
                    if tma_lokal - formula.get('b') > 0:
                        deb = formula.get('a') * (
                            tma_lokal - formula.get('b'))**formula.get('c')
                    else:
                        deb = 0
                    #dt = datetime.datetime.combine(tgl, datetime.time(0)) + jam - datetime.timedelta(hours=7)

                    _d = {
                        'sampling': int(tgl.strftime('%s')) + jam.seconds,
                        'tma': tma,
                        'debit': deb
                    }
                    series.append(
                        '{x: %(sampling)s, y: %(tma)s, debit: %(debit)s}' % _d)
                data_series[0]['series'] = '[' + ','.join(series) + ']'
        else:
            series = []
            for tgl, jam, tma in data_series[0].get('series'):
                #dt = datetime.datetime.combine(tgl, datetime.time(0)) + jam - datetime.timedelta(hours=7)
                #epoch = datetime.datetime.utcfromtimestamp(0)

                #_d = {'sampling': timedelta_total_seconds((dt - epoch)),
                #        'tma': tma}
                _d = {
                    'sampling': int(tgl.strftime('%s')) + jam.seconds,
                    'tma': tma
                }
                series.append('{x: %(sampling)s, y: %(tma)s}' % _d)
            data_series[0]['series'] = '[' + ','.join(series) + ']'

        # mencari data CH
        data_ch = {'nama': '', 'series': [], 'satuan': 'mm'}
        if pos.table_name in CAUSE_TABLE.keys():
            ch_list = CAUSE_TABLE.get(pos.table_name)
            AGENT_TABLE = dict([
                (a.table_name, a.AgentId) for a in Agent.select(
                    OR(Agent.q.AgentType == 0, Agent.q.AgentType == 1,
                       Agent.q.AgentType == 2))
            ])
            for ch in ch_list:
                print 'CH', ch
                pos_ch = Agent.get(AGENT_TABLE.get(ch))
                ch_trend = pos_ch.get_log(dari, hingga, False)
                series = [(int(a[0].strftime('%s')) + a[1].seconds,
                           float(a[2] or 0)) for a in ch_trend]
                for s in series:
                    nilai = ch_patt.get(s[0])
                    if not nilai:
                        ch_patt[s[0]] = s[1]
                    else:
                        ch_patt[s[0]] = nilai > s[1] and nilai or s[1]
                _t = {'nama': pos_ch.cname, 'series': series}
                #print ch, _t['series']
                if not _t.get('series'):
                    _t['series'] = []
                data_ch['nama'] += ', ' + pos_ch.cname
            data_ch['series'] = '[' + ','.join(
                ['{x: %s, y: %s}' % (k, v) for k, v in ch_patt.items()]) + ']'
        data_series.append(data_ch)
        #        print len(data_series[0]['series'])

        return render.tma.show_tma_ch({
            'pos': pos,
            'data': data_series,
            'dari': dari,
            'hingga': hingga,
            'pics': pics
        })
Beispiel #18
0
    def GET(self, oid):
        try:
            bendung = Agent.get(int(oid))
        except SQLObjectNotFound:
            return web.notfound()

        inp = web.input()
        if inp.get('periode'):
            periode = to_date(inp.periode)
        else:
            periode = datetime.date.today()
        year = datetime.date.today().year
        if periode.month < 11 and periode.year == year:
            periode = datetime.date(periode.year - 1, 11,
                                    1)  # 1 Nop tahun lalu
            year = datetime.date.today().year
            start = datetime.date(year=year - 1, month=11, day=1)
        if periode.month > 10 and periode.year == year:
            periode = datetime.date(periode.year, 11, 1)  # 1 Nop tahun lalu
            year = datetime.date.today().year + 1
            start = datetime.date(year=year - 1, month=11, day=1)
        if periode.month < 11 and periode.year > year:
            periode = datetime.date(periode.year - 1, 11, 1)
            year = datetime.date.today().year + 1
            start = datetime.date(year=year - 1, month=11, day=1)
        if periode.month > 10 and periode.year > year:
            periode = datetime.date(periode.year, 11, 1)
            year = datetime.date.today().year
            start = datetime.date(year=year - 1, month=11, day=1)
        if periode.month < 11 and periode.year < year:
            periode = datetime.date(periode.year - 1, 11, 1)
            year = datetime.date.today().year + 1
            start = datetime.date(year=year - 1, month=11, day=1)
        if periode.month > 10 and periode.year < year:
            periode = datetime.date(periode.year, 11, 1)
            year = datetime.date.today().year
            start = datetime.date(year=year - 1, month=11, day=1)

        #print start
        oneday = datetime.timedelta(days=1)
        oneweek = datetime.timedelta(days=7)

        while start.weekday() != 0:
            start += oneday

        days = []
        while start.year <= year:
            days.append(start.strftime("%Y-%m-%d"))
            start += oneweek
            if start.month == 11 and start.year == year:
                break

        sql = "SELECT waktu, a1, b1, c1, a2, b2, c2, a3, b3, c3, a4, b4, c4, a5, b5, c5, vnotch_q1, vnotch_q2, vnotch_q3, vnotch_tin1, vnotch_tin2, vnotch_tin3 \
                FROM waduk_daily \
                WHERE waktu IN (%s) AND pos_id=%s \
                ORDER BY waktu" % (','.join(["'" + str(i) + "'"
                                             for i in days]), oid)

        rst2 = Agent._connection.queryAll(sql)

        #periode = datetime.date.today()

        #        if periode.month < 11:

        #periode = datetime.date(periode.year - 1, 11, 1) # 1 Nop tahun lalu

        #        else:
        #            periode = datetime.date(periode.year, 11, 1)

        tanggal = periode
        if periode.month > 10:
            tanggal = datetime.date(tanggal.year + 1, 11, 1)

        if tanggal.year <= 2018:
            jhar = [30, 31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31]
            rr = []
            for i in range(12):
                rr.append(periode.replace(day=1))
                rr.append(periode.replace(day=16))
                periode += datetime.timedelta(days=jhar[i])
        if tanggal.year > 2018:
            jhar = [30, 31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31]
            rr = []
            for i in range(12):
                rr.append(periode.replace(day=15))
                rr.append(periode.replace(day=jhar[i]))
                periode += datetime.timedelta(days=jhar[i])

        sql = "SELECT waktu, po_tma, po_inflow_q, po_inflow_v, \
                po_outflow_q, po_outflow_v, \
                tma6, vol6, inflow_q, inflow_v, intake_q, intake_v, po_bona, po_bonb, vol_bona, vol_bonb \
                FROM waduk_daily \
                WHERE waktu IN (%s) AND pos_id=%s \
                ORDER BY waktu" % (','.join(["'" + str(i) + "'"
                                             for i in rr]), oid)

        rst1 = Agent._connection.queryAll(sql)

        meta = {
            'rst1': rst1,
            'rst2': rst2,
            'dari': periode,
            'hingga': periode,
            'tanggal': tanggal
        }
        return render.bendungan.keamanan.piezometerr(bendung, meta)
Beispiel #19
0
    def GET(self, oid):
        try:
            bendung = Agent.get(int(oid))
        except SQLObjectNotFound:
            return web.notfound()

        inp = web.input()
        if inp.get('periode'):
            periode = to_date(inp.periode)
        else:
            periode = datetime.date.today()
        year = datetime.date.today().year
        if periode.month < 11 and periode.year == year:
            periode = datetime.date(periode.year - 1, 11,
                                    1)  # 1 Nop tahun lalu
            year = datetime.date.today().year
            start = datetime.date(year=year - 1, month=11, day=1)
        if periode.month > 10 and periode.year == year:
            periode = datetime.date(periode.year, 11, 1)  # 1 Nop tahun lalu
            year = datetime.date.today().year + 1
            start = datetime.date(year=year - 1, month=11, day=1)
        if periode.month < 11 and periode.year > year:
            periode = datetime.date(periode.year - 1, 11, 1)
            year = datetime.date.today().year + 1
            start = datetime.date(year=year - 1, month=11, day=1)
        if periode.month > 10 and periode.year > year:
            periode = datetime.date(periode.year, 11, 1)
            year = datetime.date.today().year
            start = datetime.date(year=year - 1, month=11, day=1)
        if periode.month < 11 and periode.year < year:
            periode = datetime.date(periode.year - 1, 11, 1)
            year = datetime.date.today().year + 1
            start = datetime.date(year=year - 1, month=11, day=1)
        if periode.month > 10 and periode.year < year:
            periode = datetime.date(periode.year, 11, 1)
            year = datetime.date.today().year
            start = datetime.date(year=year - 1, month=11, day=1)

        #print start
        oneday = datetime.timedelta(days=1)
        oneweek = datetime.timedelta(days=7)

        while start.weekday() != 0:
            start += oneday

        days = []
        while start.year <= year:
            days.append(start.strftime("%Y-%m-%d"))
            start += oneweek
            if start.month == 11 and start.year == year:
                break
        #print days

        sql = "SELECT waktu, a1, b1, c1, a2, b2, c2, a3, b3, c3, a4, b4, c4, a5, b5, c5, vnotch_q1, vnotch_q2, vnotch_q3, vnotch_tin1, vnotch_tin2, vnotch_tin3 \
                FROM waduk_daily \
                WHERE waktu IN (%s) AND pos_id=%s \
                ORDER BY waktu" % (','.join(["'" + str(i) + "'"
                                             for i in days]), oid)

        rst2 = Agent._connection.queryAll(sql)

        #-----menambahkan nilai curah hujan keesokan hari nya(manipulasi database hujan)------
        j = []
        for f in rst2:
            j.append(f[0])

        day_ch = []
        for dch in j:
            d_ch = dch + datetime.timedelta(days=1)
            day_ch.append(d_ch)

        c_h = []
        for a in day_ch:
            wd = WadukDaily.select(
                AND(WadukDaily.q.waktu == a, WadukDaily.q.pos == oid))
            try:
                wdch = wd[0].curahhujan
            except IndexError:
                wdch = None
            c_h.append(wdch)

        z = []
        for b, d in zip(rst2, c_h):
            z.append((b, d))

        #print rst2

        #periode = datetime.date.today()
        #periode = datetime.date(periode.year - 1, 11, 1) # 1 Nop tahun lalu

        tanggal = periode
        if periode.month > 10:
            tanggal = datetime.date(tanggal.year + 1, 11, 1)

        if tanggal.year <= 2018:
            jhar = [30, 31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31]
            rr = []
            for i in range(12):
                rr.append(periode.replace(day=1))
                rr.append(periode.replace(day=16))
                periode += datetime.timedelta(days=jhar[i])
        if tanggal.year > 2018:
            jhar = [30, 31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31]
            rr = []
            for i in range(12):
                rr.append(periode.replace(day=15))
                rr.append(periode.replace(day=jhar[i]))
                periode += datetime.timedelta(days=jhar[i])

        sql = "SELECT waktu, po_tma, po_inflow_q, po_inflow_v, \
                po_outflow_q, po_outflow_v, \
                tma6, vol6, inflow_q, inflow_v, intake_q, intake_v, po_bona, po_bonb, vol_bona, vol_bonb \
                FROM waduk_daily \
                WHERE waktu IN (%s) AND pos_id=%s \
                ORDER BY waktu" % (','.join(["'" + str(i) + "'"
                                             for i in rr]), oid)

        rst1 = Agent._connection.queryAll(sql)

        meta = {
            'rst1': rst1,
            'rst2': z,
            'dari': periode,
            'hingga': periode,
            'tanggal': tanggal
        }
        return render.bendungan.keamanan.vnotchh(bendung, meta)
Beispiel #20
0
 def tma_monthly(self, oid, tahun, bulan):
     '''Return http response TMA monthly on Pos oid'''
     bd = Agent.get(int(oid))
     return render.bendungan.monthly(bd, {})
Beispiel #21
0
def test_segmented_klimatologi():
    tgl = datetime.date(2017, 9, 23)
    pabelan = Agent.get(9)
    jurug = Agent.get(2)
    print 'Pabelan', pabelan.get_segmented_klimatologi(tgl)
    print 'Jurug', jurug.get_segmented_klimatologi(tgl)
Beispiel #22
0
    def GET(self, oid):
        try:
            bd = Agent.get(oid)
            if bd.AgentType != 3:
                raise web.notfound(404)
        except:
            raise web.notfound(404)
        tanggal = web.input().get('d')
        if not tanggal:
            tanggal = datetime.date.today()
        else:
            try:
                tanggal = datetime.datetime.strptime(tanggal,
                                                     "%Y-%m-%d").date()
            except:
                tanggal = datetime.datetime.strptime(tanggal,
                                                     "%d %b %y").date()
        sebelum = tanggal - datetime.timedelta(days=1)
        sesudah = tanggal + datetime.timedelta(days=1)
        # '#248F8F', '#70DBDB', '#EBFAFA'
        try:
            bendungan = Agent.get(int(oid))
            if bendungan.AgentType != 3:
                raise SQLObjectNotFound
        except SQLObjectNotFound:
            return web.notfound(404)
        plotlines = ""
        tma = bendungan.get_segmented_tma_bendungan(tanggal)
        series = [[float(v), float(k)] for k, v in tma.get('kapasitas_series')]
        elev_series = []
        if tma.get('elevasi'):
            plotlines = "{ value: \
                " + str(tma.get('elevasi') or 0) + "\
                , color: '#cc0000', width: 2, label: {text: '+"

            +str(tma.get('elevasi') or 0) + "', style: {fontSize: 24}}}, "
            elev_series = [[e[0], tma.get('elevasi') or 0] for e in series]

        return render.bendungan.lengkung_kapasitas(
            bendungan,
            meta={
                'now':
                tanggal.strftime('%d %b %y'),
                'before':
                sebelum.strftime('%d %b %y'),
                'after':
                sesudah.strftime('%d %b %y'),
                'categories1':
                [float(d[1]) for d in tma.get('kapasitas_series')],
                'categories': [],
                's_ma_min':
                0.8,
                's_ma_normal':
                10 / (bendungan.siaga3 / bendungan.siaga4) *
                (bendungan.siaga1 - bendungan.siaga4),
                's_ma_banjir':
                10.8,
                'series':
                series,
                'elev_series':
                elev_series,
                'plotlines':
                plotlines,
                'tma':
                tma
            })