Best Python code snippet using fMBT_python
APP.py
Source:APP.py  
1import os2import flask3import dash4import dash_daq as daq5import dash_core_components as dcc6import dash_html_components as html7import pandas as pd89#lecture et initialisation des données10df = pd.read_csv('data.csv', delimiter=',', names=['year','temperature','moisture','humidity'])1112def render_gauge(name, parameter, unit):13    return daq.Gauge(14      className= 'gauge',15      label = name,16      value = df.loc[len(df)-1, parameter],17      max = 100,18      min = 0,19      showCurrentValue = True,20      units = unit,21      color = {"gradient":True,"ranges":{"green":[0,60],"yellow":[60,80],"red":[80,100]}},22      scale = {'start':0, 'interval': 5},23      )24config = {'displayModeBar': False,'displaylogo': False, 'scrollZoom': True}25def render_graph(yvalue, label):26    return dcc.Graph(  27        config= config,28        figure =dict(29            data=[30                dict(31                    x=df['year'], y=df[yvalue], type='bar',32                )33            ],34            layout=dict(35                title = label + ' VS Temps',36                xaxis = dict(37                    title= 'Temps',38                    titlefont=dict(39                        family = 'Arial',40                        size = 20,41                        color = '#7FDBFF'42                        )43                    ),44                yaxis = dict(45                    title= label,46                    titlefont=dict(47                        family = 'Arial',48                        size = 20,49                        color = '#7FDBFF'50                        )51                    ),52                plot_bgcolor= '#1d242e',53                paper_bgcolor= '#1d242e',54                font= {'color': '#7FDBFF'},                                                     55            )56        ),57        style={'overflowX':'scroll'},58        id= "graph"+label,59    )6061#initialisation de la page dash62app = dash.Dash(__name__, title='UI pour IRESEN',63             meta_tags=[{"name":"description","content":"my UI app"},{"name": "viewport", "content": "width=device-width, initial-scale=1"}])64server = app.server 6566#visualisation de la page67app.layout =html.Div(68    [	69        html.Header(className="flex-display row", children=[70            html.Img(src=app.get_asset_url('domaines.webp'), className='icon', alt='icone des domaines'),71            html.Div(className='seven columns', children=[72                html.H1('Interface graphique pour serre intelligente', style={'textAlign': 'center', 'margin-top':'30px'}),73                html.Br(),74                html.H6('Visualisation des paramètres avec un serveur local', style={'textAlign': 'center', 'padding': 5}),75            ]),76            html.Img(src=app.get_asset_url("Iresen.webp"), className='icon_iresen', alt='icone IRESEN'),77        ]),78        html.Main([79            dcc.Tabs(id='tabs', value='tab_1', className='tabs-container', parent_className='custom-tabs', children=[80                dcc.Tab(label='Vue générale', value='tab_1', className='custom-tab', selected_className='custom-tab--selected', children=[81                    html.Div(className='six columns', children=[82                        html.H2(children='Image de la serre', className='twelve columns', style={'textAlign':'center'}),83                        html.Img(src=app.get_asset_url('serre.webp'), className='serre', alt='image de la serre'),84                    ]),85                    html.Div(className='six columns', children=[86                        html.H2(children='Valeur des capteurs', className='twelve columns', style={'textAlign':'center'}),87                        html.Div([88                        render_gauge('Humidité du sol', 'moisture', '%'),89                        render_gauge('Température du sol', 'temperature', '°C'),90                        render_gauge('Température ambiante', 'temperature', '°C'),91                        render_gauge('Ensoleillement','moisture', '%'),92                        render_gauge('CO2', 'humidity','mg/L'),93                        render_gauge('Humidité relative', 'humidity', '%'),94                        ])95                    ]),96                ]),97                dcc.Tab(label='Humidité du sol', className='custom-tab', selected_className='custom-tab--selected', children=[98                    html.Div(className= 'three columns', children=[99                        html.H4(children='Emplacement des capteurs',className='twelve columns', style={'margin-left':20,'textAlign': 'center'}),100                        html.Img(src=app.get_asset_url('serre moist.webp'), className='img_sensor', alt='image de la serre'),101                    ]),102                    html.Div(className='six columns', children=[103                        html.H4(children='Humidité du sol', style={'textAlign': 'center'}),104                        html.Div(className='offset-by-four columns',children=[105                            render_gauge('', 'moisture', '%')106                        ])107                    ]),108                    html.Div(className='three columns', children=[109                        html.H4(children='Image du capteur'),110                        html.Img(src=app.get_asset_url('moisture.webp'), className='img_capt', alt='image du capteur'),111                    ]),112                    html.Div(className='twelve columns', children=[113                            render_graph('moisture','Humidité du sol')114                    ])115                ]),116                dcc.Tab(label='Température du sol', className='custom-tab', selected_className='custom-tab--selected', children=[117                    html.Div(className= 'three columns', children=[118                        html.H4(children='Emplacement des capteurs', style={'textAlign': 'center', 'margin-left':20}),119                        html.Img(src=app.get_asset_url('serre temp.webp'), className='img_sensor', alt='image de la serre'),120                    ]),121                    html.Div(className='six columns', children=[122                        html.H4(children='Température du sol', style={'textAlign': 'center'}),123                        html.Div(className='offset-by-four columns',children=[124                            render_gauge('','temperature','°C')125                        ])126                    ]),127                    html.Div(className='three columns', children=[128                        html.H4(children='Image du capteur'),129                        html.Img(src=app.get_asset_url('temp.webp'), className='img_capt', alt='image du capteur'),130                    ]),131                    html.Div(className='twelve columns', children=[132                        render_graph('temperature','Température du sol')              133                    ])134                ]),135                dcc.Tab(label='Température ambiante', className='custom-tab', selected_className='custom-tab--selected', children=[136                    html.Div(className= 'three columns', children=[137                        html.H4(children='Emplacement des capteurs', style={'textAlign': 'center', 'margin-left':20}),138                        html.Img(src=app.get_asset_url('serre both.webp'), className='img_sensor', alt='image de la serre'),139                    ]),140                    html.Div(className='six columns', children=[141                        html.H4(children='Température ambiante', style={'textAlign': 'center'}),142                        html.Div(className='offset-by-four columns',children=[143                            render_gauge('','temperature','°C')144                        ])145                    ]),146                    html.Div(className='three columns', children=[147                        html.H4(children='Image du capteur'),148                        html.Img(src=app.get_asset_url('temp and humidity.webp'), className='img_capt', alt='image du capteur'),149                    ]),150                    html.Div(className='twelve columns', children=[151                        render_graph('temperature','Température ambiante')152                    ])153                ]),154                dcc.Tab(label='Ensoleillement', className='custom-tab', selected_className='custom-tab--selected', children=[155                    html.Div(className= 'three columns', children=[156                        html.H4(children='Emplacement des capteurs', style={'textAlign': 'center', 'margin-left':20}),157                        html.Img(src=app.get_asset_url('serre enso.webp'), className='img_sensor', alt='image de la serre'),158                    ]),159                    html.Div(className='six columns', children=[160                        html.H4(children='Ensoleillement', style={'textAlign': 'center'}),161                        html.Div(className='offset-by-four columns',children=[162                            render_gauge('','temperature','%')163                        ])164                    ]),165                    html.Div(className='three columns', children=[166                        html.H4(children='Image du capteur'),167                        html.Img(src=app.get_asset_url('ensoleillement.webp'), className='img_capt', alt='image du capteur'),168                    ]),169                    html.Div(className='twelve columns', children=[170                        render_graph('humidity','Ensoleillement')171                    ])172                ]),173                dcc.Tab(label='CO2', className='custom-tab', selected_className='custom-tab--selected', children=[174                    html.Div(className= 'three columns', children=[175                        html.H4(children='Emplacement des capteurs', style={'textAlign': 'center', 'margin-left':20}),176                        html.Img(src=app.get_asset_url('serre co.webp'), className='img_sensor', alt='image de la serre'),177                    ]),178                    html.Div(className='six columns', children=[179                        html.H4(children='CO2', style={'textAlign': 'center'}),180                        html.Div(className='offset-by-four columns',children=[181                            render_gauge('','moisture','%')182                        ])183                    ]),184                    html.Div(className='three columns', children=[185                        html.H4(children='Image du capteur'),186                        html.Img(src=app.get_asset_url('CO2.webp'), className='img_capt', alt='image du capteur'),187                    ]),188                    html.Div(className='twelve columns', children=[189                        render_graph('moisture','CO2')190                    ])191                ]),      192                dcc.Tab(label='Humidité relative', className='custom-tab', selected_className='custom-tab--selected', children=[193                    html.Div(className= 'three columns', children=[194                        html.H4(children='Emplacement des capteurs', style={'textAlign': 'center', 'margin-left':20}),195                        html.Img(src=app.get_asset_url('serre both.webp'), className='img_sensor', alt='image de la serre'),196                    ]),197                    html.Div(className='six columns', children=[198                        html.H4(children='Humidité relative', style={'textAlign': 'center'}),199                        html.Div(className='offset-by-four columns',children=[200                            render_gauge('','humidity','%')201                        ])202                    ]),203                    html.Div(className='three columns', children=[204                        html.H4(children='Image du capteur'),205                        html.Img(src=app.get_asset_url('temp and humidity.webp'), className='img_capt', alt='image du capteur'),206                    ]),207                    html.Div(className='twelve columns', children=[208                        render_graph('humidity','Humidité relative')209                    ])210                ]),      211        ])212    ])213])214215216class MyFlask(flask.Flask):217    def get_send_file_max_age(self, name):218        if name.lower().endswith('.webp'):219            return 60220        if name.lower().endswith('.css?m=1596413279.0'):221        	return 60222        return flask.Flask.get_send_file_max_age(self, name)223224@server.route('/assets/<path:path>')225def serve_static(path):226	root_dir = os.getcwd()227	return flask.send_from_directory(os.path.joint(root_dir, 'assets'),path)228229if __name__ == '__main__':
...modelPredict2.py
Source:modelPredict2.py  
1import dash_core_components as dcc2import dash_html_components as html3def renderModelPredict() :4    return html.Div([5                html.H1('Test Saham', className='h1'),6                 html.Div(children=[7                    html.Div([8                        html.P('Tanggal mulai prediksi : ')9                     ],className='col-2'),10                    html.Div([11                        dcc.Input(id='datein', type='number', value='12')12                    ],className='col-4'),13                    html.Div([14                        html.P('Tanggal akhir prediksi : ')15                     ],className='col-2'),16                    html.Div([17                        dcc.Input(id='dateout', type='number', value='12')18                    ],className='col-4'),19                    html.Div([20                        html.P('Bulan mulai prediksi : ')21                     ],className='col-2'),22                    html.Div([23                        dcc.Input(id='monthin', type='number', value='12')24                    ],className='col-4'),25                    html.Div([26                        html.P('Bulan akhir prediksi : ')27                     ],className='col-2'),28                    html.Div([29                        dcc.Input(id='monthout', type='number', value='12')30                    ],className='col-4'),31                    html.Div([32                        html.P('Tahun mulai prediksi : ')33                     ],className='col-2'),34                    html.Div([35                        dcc.Input(id='yearin', type='number', value='2000')36                    ],className='col-4'),37                    html.Div([38                        html.P('Tahun akhir prediksi : ')39                     ],className='col-2'),40                    html.Div([41                        dcc.Input(id='yearout', type='number', value='2100')42                    ],className='col-4'),43                    html.Div([44                        html.P('Data Train : ')45                     ],className='col-2'),46                    html.Div([47                        dcc.Input(id='train', type='number', value='1000')48                    ],className='col-4'),49                    html.Div([50                        html.P('Data Test : ')51                     ],className='col-2'),52                    html.Div([53                        dcc.Input(id='test', type='number', value='1000')54                    ],className='col-4'),55                    html.Div([56                        html.P('Symbol saham : ')57                     ],className='col-2'),58                    html.Div([59                        dcc.Input(id='symbol', type='text')60                    ],className='col-4'),61                    html.Div([62                        html.P('Jenis Machine Learning : ')63                     ],className='col-2'),64                    html.Div([65                        dcc.Dropdown(id='ML', options=[66                            {'label' : 'Moving Averange', 'value' : 'MA'},67                            {'label' : 'Linear Regresression', 'value' : 'LR'},68                            {'label' : 'On Proggress', 'value' : 'KNN'},69                            {'label' : 'On Proggress', 'value' : 'AA'},70                            {'label' : 'On Proggress', 'value' : 'LSTM'}71                        ], value='None.1' )72                    ],className='col-4'),73                    html.Div([74                        html.A("Daftar Kode Saham", href='https://www.idx.co.id/data-pasar/data-saham/daftar-saham/', target="_blank")75                    ],className='col-2'),76                    html.Div([77                        html.Button('Predict', type='submit', id='buttonPredict', className='btn btn-primary')78                        # html.A(79                        #     html.Button('Predict', id='buttonPredict', className='btn btn-primary'),80                        #     href = 'http://127.0.0.1:2019/'81                        # )82                    ],className='mx-auto', style={ 'paddingTop': '20px', 'paddingBottom': '20px' })83                ],className='row'),84                html.Div([85                    html.H2('', id='outputPredict', className='mx-auto')86                ], className='row')87            ])88                    89def renderModelPredict1() :90    return html.Div([91                html.H1('Test Saham 2', className='h1'),92                 html.Div(children=[93                    html.Div([94                        html.P('Tanggal mulai prediksi : ')95                     ],className='col-2'),96                    html.Div([97                        dcc.Input(id='datein1', type='number', value='12')98                    ],className='col-4'),99                    html.Div([100                        html.P('Tanggal akhir prediksi : ')101                     ],className='col-2'),102                    html.Div([103                        dcc.Input(id='dateout1', type='number', value='12')104                    ],className='col-4'),105                    html.Div([106                        html.P('Bulan mulai prediksi : ')107                     ],className='col-2'),108                    html.Div([109                        dcc.Input(id='monthin1', type='number', value='12')110                    ],className='col-4'),111                    112                    html.Div([113                        html.P('Bulan akhir prediksi : ')114                     ],className='col-2'),115                    html.Div([116                        dcc.Input(id='monthout1', type='number', value='12')117                    ],className='col-4'),118                    html.Div([119                        html.P('Tahun mulai prediksi : ')120                     ],className='col-2'),121                    html.Div([122                        dcc.Input(id='yearin1', type='number', value='2000')123                    ],className='col-4'),124                    html.Div([125                        html.P('Tahun akhir prediksi : ')126                     ],className='col-2'),127                    html.Div([128                        dcc.Input(id='yearout1', type='number', value='2100')129                    ],className='col-4'),130                    html.Div([131                        html.P('Data Train : ')132                     ],className='col-2'),133                    html.Div([134                        dcc.Input(id='train1', type='number', value='1000')135                    ],className='col-4'),136                    html.Div([137                        html.P('Data Test : ')138                     ],className='col-2'),139                    html.Div([140                        dcc.Input(id='test1', type='number', value='1000')141                    ],className='col-4'),142                    html.Div([143                        html.P('Symbol saham : ')144                     ],className='col-2'),145                    html.Div([146                        dcc.Input(id='symbol1', type='text')147                    ],className='col-4'),148                    html.Div([149                        html.P('Jenis Machine Learning : ')150                     ],className='col-2'),151                    html.Div([152                        dcc.Dropdown(id='ML1', options=[153                            {'label' : 'Moving Averange', 'value' : 'MA'},154                            {'label' : 'Linear Regresression', 'value' : 'LR'},155                            {'label' : 'On Proggress', 'value' : 'KNN'},156                            {'label' : 'On Proggress', 'value' : 'AA'},157                            {'label' : 'On Proggress', 'value' : 'LSTM'}158                        ], value='None.1' )159                    ],className='col-4'),160                    html.Div([161                        html.Button('Predict', type='submit', id='buttonPredict1', className='btn btn-primary')162                        # html.A(163                        #     html.Button('Predict', id='buttonPredict', className='btn btn-primary'),164                        #     href = 'http://127.0.0.1:2019/'165                        # )166                    ],className='mx-auto', style={ 'paddingTop': '20px', 'paddingBottom': '20px' })167                ],className='row'),168                html.Div([169                    html.H2('', id='outputPredict1', className='mx-auto')170                ], className='row')171            ])172                  173def renderModelPredict2() :174    return html.Div([175                html.H1('Test Saham Trading Signal', className='h1'),176                 html.Div(children=[177                    html.Div([178                        html.P('Tanggal mulai prediksi : ')179                     ],className='col-2'),180                    html.Div([181                        dcc.Input(id='datein2', type='number', value='12')182                    ],className='col-4'),183                    html.Div([184                        html.P('Tanggal akhir prediksi : ')185                     ],className='col-2'),186                    html.Div([187                        dcc.Input(id='dateout2', type='number', value='12')188                    ],className='col-4'),189                    html.Div([190                        html.P('Bulan mulai prediksi : ')191                     ],className='col-2'),192                    html.Div([193                        dcc.Input(id='monthin2', type='number', value='12')194                    ],className='col-4'),195                    196                    html.Div([197                        html.P('Bulan akhir prediksi : ')198                     ],className='col-2'),199                    html.Div([200                        dcc.Input(id='monthout2', type='number', value='12')201                    ],className='col-4'),202                    html.Div([203                        html.P('Tahun mulai prediksi : ')204                     ],className='col-2'),205                    html.Div([206                        dcc.Input(id='yearin2', type='number', value='2000')207                    ],className='col-4'),208                    html.Div([209                        html.P('Tahun akhir prediksi : ')210                     ],className='col-2'),211                    html.Div([212                        dcc.Input(id='yearout2', type='number', value='2100')213                    ],className='col-4'),214                    html.Div([215                        html.P('Symbol saham : ')216                     ],className='col-2'),217                    html.Div([218                        dcc.Input(id='symbol2', type='text')219                    ],className='col-4'),220                    html.Div([221                        html.P('Cash (0-100000): ')222                     ],className='col-2'),223                    html.Div([224                        dcc.Input(id='cash', type='number', value='100000')225                    ],className='col-4'),226                    html.Div([227                        html.P('Stoploss (0.1-0.9) : ')228                     ],className='col-2'),229                    html.Div([230                        dcc.Input(id='stoploss', type='number', value='1000')231                    ],className='col-4'),232                    html.Div([233                        html.P('batch (0-10000): ')234                     ],className='col-2'),235                    html.Div([236                        dcc.Input(id='batch', type='text')237                    ],className='col-4'),238                    html.Div([239                        html.P('Port Value (0.1-0.9): ')240                     ],className='col-2'),241                    html.Div([242                        dcc.Input(id='portvalue', type='text')243                    ],className='col-4'),244                    html.Div([245                        html.Button('Predict', type='submit', id='buttonPredict2', className='btn btn-primary')246                        # html.A(247                        #     html.Button('Predict', id='buttonPredict', className='btn btn-primary'),248                        #     href = 'http://127.0.0.1:2019/'249                        # )250                    ],className='mx-auto', style={ 'paddingTop': '20px', 'paddingBottom': '20px' })251                ],className='row'),252                html.Div([253                    html.H2('', id='outputPredict2', className='mx-auto')254                ], className='row')255            ])...eval_det.py
Source:eval_det.py  
1""" 2    Generic Code for Object Detection Evaluation3    From: https://github.com/facebookresearch/votenet/blob/master/utils/eval_det.py4    Input:5    For each class:6        For each image:7            Predictions: box, score8            Groundtruths: box9    10    Output:11    For each class:12        precision-recal and average precision13    14    Author: Charles R. Qi15    16    Ref: https://raw.githubusercontent.com/rbgirshick/py-faster-rcnn/master/lib/datasets/voc_eval.py17"""18import numpy as np19def voc_ap(rec, prec, use_07_metric=False):20    """ ap = voc_ap(rec, prec, [use_07_metric])21    Compute VOC AP given precision and recall.22    If use_07_metric is true, uses the23    VOC 07 11 point method (default:False).24    """25    if use_07_metric:26        # 11 point metric27        ap = 0.28        for t in np.arange(0., 1.1, 0.1):29            if np.sum(rec >= t) == 0:30                p = 031            else:32                p = np.max(prec[rec >= t])33            ap = ap + p / 11.34    else:35        # correct AP calculation36        # first append sentinel values at the end37        mrec = np.concatenate(([0.], rec, [1.]))38        mpre = np.concatenate(([0.], prec, [0.]))39        # compute the precision envelope40        for i in range(mpre.size - 1, 0, -1):41            mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])42        # to calculate area under PR curve, look for points43        # where X axis (recall) changes value44        i = np.where(mrec[1:] != mrec[:-1])[0]45        # and sum (\Delta recall) * prec46        ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])47    return ap48import os49import sys50BASE_DIR = os.path.dirname(os.path.abspath(__file__))51from utils.metric_util import calc_iou # axis-aligned 3D box IoU52def get_iou(bb1, bb2):53    """ Compute IoU of two bounding boxes.54        ** Define your bod IoU function HERE **55    """56    #pass57    iou3d = calc_iou(bb1, bb2)58    return iou3d59from utils.box_util import box3d_iou60def get_iou_obb(bb1,bb2):61    iou3d = box3d_iou(bb1,bb2)62    return iou3d63def get_iou_main(get_iou_func, args):64    return get_iou_func(*args)65def eval_det_cls(pred, gt, ovthresh=0.25, use_07_metric=False, get_iou_func=get_iou):66    """ Generic functions to compute precision/recall for object detection67        for a single class.68        Input:69            pred: map of {img_id: [(bbox, score)]} where bbox is numpy array70            gt: map of {img_id: [bbox]}71            ovthresh: scalar, iou threshold72            use_07_metric: bool, if True use VOC07 11 point method73        Output:74            rec: numpy array of length nd75            prec: numpy array of length nd76            ap: scalar, average precision77    """78    # construct gt objects79    class_recs = {} # {img_id: {'bbox': bbox list, 'det': matched list}}80    npos = 081    for img_id in gt.keys():82        bbox = np.array(gt[img_id])83        det = [False] * len(bbox)84        npos += len(bbox)85        class_recs[img_id] = {'bbox': bbox, 'det': det}86    # pad empty list to all other imgids87    for img_id in pred.keys():88        if img_id not in gt:89            class_recs[img_id] = {'bbox': np.array([]), 'det': []}90    # construct dets91    image_ids = []92    confidence = []93    BB = []94    for img_id in pred.keys():95        for box,score in pred[img_id]:96            image_ids.append(img_id)97            confidence.append(score)98            BB.append(box)99    confidence = np.array(confidence)100    BB = np.array(BB) # (nd,4 or 8,3 or 6)101    # sort by confidence102    sorted_ind = np.argsort(-confidence)103    sorted_scores = np.sort(-confidence)104    BB = BB[sorted_ind, ...]105    image_ids = [image_ids[x] for x in sorted_ind]106    # go down dets and mark TPs and FPs107    nd = len(image_ids)108    tp = np.zeros(nd)109    fp = np.zeros(nd)110    for d in range(nd):111        #if d%100==0: print(d)112        R = class_recs[image_ids[d]]113        bb = BB[d,...].astype(float)114        ovmax = -np.inf115        BBGT = R['bbox'].astype(float)116        if BBGT.size > 0:117            # compute overlaps118            for j in range(BBGT.shape[0]):119                iou = get_iou_main(get_iou_func, (bb, BBGT[j,...]))120                if iou > ovmax:121                    ovmax = iou122                    jmax = j123        #print d, ovmax124        if ovmax > ovthresh:125            if not R['det'][jmax]:126                tp[d] = 1.127                R['det'][jmax] = 1128            else:129                fp[d] = 1.130        else:131            fp[d] = 1.132    # compute precision recall133    fp = np.cumsum(fp)134    tp = np.cumsum(tp)135    rec = tp / float(npos + 1e-8)136    #print('NPOS: ', npos)137    # avoid divide by zero in case the first detection matches a difficult138    # ground truth139    prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)140    ap = voc_ap(rec, prec, use_07_metric)141    return rec, prec, ap142def eval_det_cls_wrapper(arguments):143    pred, gt, ovthresh, use_07_metric, get_iou_func = arguments144    rec, prec, ap = eval_det_cls(pred, gt, ovthresh, use_07_metric, get_iou_func)145    return (rec, prec, ap)146def eval_det(pred_all, gt_all, ovthresh=0.25, use_07_metric=False, get_iou_func=get_iou):147    """ Generic functions to compute precision/recall for object detection148        for multiple classes.149        Input:150            pred_all: map of {img_id: [(classname, bbox, score)]}151            gt_all: map of {img_id: [(classname, bbox)]}152            ovthresh: scalar, iou threshold153            use_07_metric: bool, if true use VOC07 11 point method154        Output:155            rec: {classname: rec}156            prec: {classname: prec_all}157            ap: {classname: scalar}158    """159    pred = {} # map {classname: pred}160    gt = {} # map {classname: gt}161    for img_id in pred_all.keys():162        for classname, bbox, score in pred_all[img_id]:163            if classname not in pred: pred[classname] = {}164            if img_id not in pred[classname]:165                pred[classname][img_id] = []166            if classname not in gt: gt[classname] = {}167            if img_id not in gt[classname]:168                gt[classname][img_id] = []169            pred[classname][img_id].append((bbox,score))170    for img_id in gt_all.keys():171        for classname, bbox in gt_all[img_id]:172            if classname not in gt: gt[classname] = {}173            if img_id not in gt[classname]:174                gt[classname][img_id] = []175            gt[classname][img_id].append(bbox)176    rec = {}177    prec = {}178    ap = {}179    for classname in gt.keys():180        print('Computing AP for class: ', classname)181        rec[classname], prec[classname], ap[classname] = eval_det_cls(pred[classname], gt[classname], ovthresh, use_07_metric, get_iou_func)182        print(classname, ap[classname])183    184    return rec, prec, ap 185from multiprocessing import Pool186def eval_det_multiprocessing(pred_all, gt_all, ovthresh=0.25, use_07_metric=False, get_iou_func=get_iou):187    """ Generic functions to compute precision/recall for object detection188        for multiple classes.189        Input:190            pred_all: map of {img_id: [(classname, bbox, score)]}191            gt_all: map of {img_id: [(classname, bbox)]}192            ovthresh: scalar, iou threshold193            use_07_metric: bool, if true use VOC07 11 point method194        Output:195            rec: {classname: rec}196            prec: {classname: prec_all}197            ap: {classname: scalar}198    """199    pred = {} # map {classname: pred}200    gt = {} # map {classname: gt}201    for img_id in pred_all.keys():202        for classname, bbox, score in pred_all[img_id]:203            if classname not in pred: pred[classname] = {}204            if img_id not in pred[classname]:205                pred[classname][img_id] = []206            if classname not in gt: gt[classname] = {}207            if img_id not in gt[classname]:208                gt[classname][img_id] = []209            pred[classname][img_id].append((bbox,score))210    for img_id in gt_all.keys():211        for classname, bbox in gt_all[img_id]:212            if classname not in gt: gt[classname] = {}213            if img_id not in gt[classname]:214                gt[classname][img_id] = []215            gt[classname][img_id].append(bbox)216    rec = {}217    prec = {}218    ap = {}219    p = Pool(processes=10)220    ret_values = p.map(eval_det_cls_wrapper, [(pred[classname], gt[classname], ovthresh, use_07_metric, get_iou_func) for classname in gt.keys() if classname in pred])221    p.close()222    for i, classname in enumerate(gt.keys()):223        if classname in pred:224            rec[classname], prec[classname], ap[classname] = ret_values[i]225        else:226            rec[classname] = 0227            prec[classname] = 0228            ap[classname] = 0229        print('eval per class', classname, ap[classname])230    ...ClassDictionary.py
Source:ClassDictionary.py  
1# !/usr/bin/python2# This file is part of snavtofamix (Source Navigator to FAMIX).3#4# snavtofamix is free software; you can redistribute it and/or modify it5# under the terms of the GNU General Public License as published by the6# Free Software Foundation; either version 2 of the License, or (at your7# option) any later version.8#9# snavtofamix is distributed in the hope that it will be useful, but WITHOUT10# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS11# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more12# details.13#14# You should have received a copy of the GNU General Public License along15# with snavtofamix; if not, write to the Free Software Foundation, Inc.,16# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA17#18# Copyright 2006,2007   University of Antwerp19# Author(s): Bart Van Rompaey <bart.vanrompaey2@ua.ac.be>,20#                     Bart Du Bois <bart.dubois@ua.ac.be>21from log4py import Logger22from cplusplus.data_types.ClassEntity import ClassReferenceEntity23from QualifiedNameHelperFunctions 		import 	getParentNamespaceName,\24												getNonQualifiedName25def getTemplateParameters(classData):26	return classData[0]27def getNamespaceName(classData):28	return classData[1]29def createClassData(templateParameters, namespaceName):30	return [templateParameters, namespaceName]31##32# Encapsulation of a dictionary of classes.33#34# Key: 		className35# Value:	dictionary with36#		Key:	sourceFile37#		Value: [lineNr1xClassData1,..,lineNrNxClassDataN]38#	with lineNr x classData = a dictionary with key lineNr and value classData39# 	with classData = [ templateParameters, namespaceName ]40#		with41#			templateParameters = e.g., "X" the template parameter description in string-format42#			namespaceName = the fully qualified name of the parent namespace43#44# Additional data that needs to be remembered for a class can be appended to classData.45##46class ClassDictionary:47	##48	# Initialize a dictionary.49	##50	def __init__(self):51		self.dict = {}52		self.log = Logger().get_instance(self)53	##54	# Verify whether the dictionary contains a given class-name.55	##56	def hasKey(self, className):57		return (className in self.dict)58	##59	# Add a class contained in the given sourceFile at the given line-nr to the dictionary.60	#61	# @className - the name of the class62	# @sourceFile - the name of the file in which the class is declared63	# @lineNr - the line nr at which the class is declared in the source file64	# @classData - a list with data specific for the given class65	#66	# @returns True/False indicating whether the class was added67	##68	def add(self, className, sourceFile, lineNr, classData):69		isAdded = False70		nonQualifiedClassName = getNonQualifiedName(className)71		parentNamespaceName = getParentNamespaceName(className)72		# adjust the given namespace name in case the classname73		# was qualified74		if parentNamespaceName != "":75			givenNamespaceName = getNamespaceName(classData)76			if givenNamespaceName != "":77				parentNamespaceName = givenNamespaceName + "::" + parentNamespaceName78			classData[1] = parentNamespaceName79		if ( not(nonQualifiedClassName in self.dict) ):80			self.dict[nonQualifiedClassName] = {}81		if ( not(sourceFile in self.dict[nonQualifiedClassName]) ):82			self.dict[nonQualifiedClassName][sourceFile] = {}83		if ( not(lineNr in self.dict[nonQualifiedClassName][sourceFile]) ):84			self.dict[nonQualifiedClassName][sourceFile][lineNr]=classData85			isAdded = True86		return isAdded87	def getClassesByName(self, className):88		classList = []89		if className in self.dict:90			for sourceFile in self.dict[className]:91				for lineNr in self.dict[className][sourceFile]:92					classData = self.dict[className][sourceFile][lineNr]93					classRefEntity = ClassReferenceEntity(className, getNamespaceName(classData), sourceFile, lineNr, getTemplateParameters(classData))94					classList.append(classRefEntity)95		return classList96	##97	# Retrieve a list of [sourceFile, lineNr] elements for which it holds that in98	# sourceFile at lineNr a class with name className is declared.99	#100	# @param className - the class name for which to find source locations.101	#102	# @returns a list of elements [sourceFile, lineNr]103	##104	def getSourceLocations(self, className):105		sourceLocations=[]106		if ( className in self.dict ):107			for sourceFile in self.dict[className]:108				for lineNr in self.dict[className][sourceFile]:109					sourceLocations.append([sourceFile,lineNr])110		return sourceLocations111	def getClassesByNamespace(self, className, namespaceName):112		classList = []113		classNameWithoutTemplates = className114		templatePars = ""115		if "<" in className:116			classNameWithoutTemplates = className.split("<")[0]117			templatePars = "<".join(className.split("<")[1:])118			if ">" in templatePars:119				parts = templatePars.split(">")120				templatePars = ">".join(parts[0:len(parts)-1])121		if classNameWithoutTemplates in self.dict:122			for sourceFile in self.dict[classNameWithoutTemplates]:123				for lineNr in self.dict[classNameWithoutTemplates][sourceFile]:124					classData = self.dict[classNameWithoutTemplates][sourceFile][lineNr]125					if getNamespaceName(classData) == namespaceName:126						classRefEntity = ClassReferenceEntity(className, getNamespaceName(classData), sourceFile, lineNr, getTemplateParameters(classData))127						classList.append(classRefEntity)128		return classList129	##130	# Retrieve a list with data on the class with the given properties.131	# If no such class exists, [] is returned.132	#133	# Currently, classData =  [ templateParameters ]134	# with templateParameters = e.g., "X" the template parameter description in string-format135	##136	def getClassData(self, className, sourceFile, lineNr):137		classData=[]138		if  className in self.dict :139			if sourceFile in self.dict[className]:140				if lineNr in self.dict[className][sourceFile]:141					classData = self.dict[className][sourceFile][lineNr]142		return classData143	##144	# Retrieve a reference to the unique class satisfying the given properties.145	##146	def getClassReference(self, className, sourceFile, lineNr):147		classReference = None148		if  className in self.dict :149			if sourceFile in self.dict[className]:150				if lineNr in self.dict[className][sourceFile]:151					classData = self.dict[className][sourceFile][lineNr]152					classReference = ClassReferenceEntity(className, getNamespaceName(classData), sourceFile, lineNr, getTemplateParameters(classData))153		return classReference154	##155	# Verify whether the dictionary contains an enty for the given156	# classname in the given namespaceName at the given lineNr in the given157	# sourceFile.158	#159	# This is relevant in scenario's where you do not wish to add two160	# declarations for the same parameters at different line numbers.161	##162	def containsClass(self, className, sourceFile, namespaceName):163		exists = False164		# In case there exist multiple class definitions with identical method signatures165		# in the same file, we will never be able to retrieve the right target and just166		# drop the invocations.167		if ( (className in self.dict) and (sourceFile in self.dict[className]) ):168			for anyLineNrDeclaringClassInFile in self.dict[className][sourceFile]:169				classData = self.dict[className][sourceFile][anyLineNrDeclaringClassInFile]170				if getNamespaceName(classData) == namespaceName:171					exists = True172		return exists173	174	def createLocationBasedDictionary(self):175		"""Creates a class dictionary source location as key and class name as value"""176		locClDict = {}177		for className in self.dict:178			for sourceFile in self.dict[className]:179				for lineNr in self.dict[className][sourceFile]:180					loc = sourceFile+":"+lineNr181					if loc in locClDict:182						locClDict[loc].append(className)183					else:184						locClDict[loc] = [ className ]185		return locClDict186					187	##188	# Print the contents of the dictionary in the following formats.189	##190	def printContent(self):191		self.log.info( "ClassDictionary contents:")192		for className in self.dict:193			for sourceFile in self.dict[className]:194				for lineNr in self.dict[className][sourceFile]:...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
