Welcome    Usage    Browse    Find CID    Search     Log in

cM API Documentation

module.py

Go to the documentation of this file.
00001 #
00002 # Collective Mind
00003 #
00004 # See cM LICENSE.txt for licensing details.
00005 # See cM Copyright.txt for copyright details.
00006 #
00007 # Developer(s): (C) Grigori Fursin, started on 2011.09
00008 #
00009 
00010 # Should always be here
00011 ini={}
00012 cm_kernel=None
00013 
00014 # Local settings
00015 import copy
00016 import time
00017 import json
00018 import random
00019 
00020 # ============================================================================
00021 def init(i):
00022     return {'cm_return':0}
00023 
00024 # ============================================================================
00025 def scenario(i):
00026     """
00027     Build and run program, save to repository
00028 
00029     Input:  {
00030               caller_module_uid    - caller module UID
00031               state                - pipeline state
00032               exploration_scenario - exploraiton scenario parameters
00033               summary_point        - summary dimensions describing aggregated point
00034               aggregated_entry     - all aggregated points
00035               space                - if aggregated, current space
00036               original_input       - to get other additional forms per scenario
00037               cm_data_desc         - data description (from the original form)
00038               cm_form_explore      - form explore (form the original form)
00039               number_of_iterations - max number of iterations
00040             }
00041 
00042     Output: {
00043               cm_return   - if =0, success
00044             }
00045     """
00046 
00047     # Exploration scenarion parameters
00048     es=i.get('exploration_scenario',{})
00049     sr=es.get('save_results_in_repository','')
00050     aggr=es.get('aggregate_in_one_entry','')
00051     wrepo=es.get('work_repo_uoa','')
00052     lwrepo=es.get('work_repo_uoa','')
00053     pmd=i.get('pipeline_module_desc',{})
00054 
00055     desc=i.get('cm_data_desc',{})
00056     desc_copy=copy.deepcopy(desc) # description will be dynamically changing
00057                                   # this is the original one
00058 
00059     state_orig=i.get('state',{})
00060     state=copy.deepcopy(state_orig) # not to mix up original state
00061                                     # otherwise some strange aggregations of datasets, flags, etc
00062     ae=i.get('aggregated_entry',{})
00063 
00064     # Get path of aggregated LOCAL entry
00065     dae={}
00066     if aggr=='yes' and len(ae)>0:
00067        r=cm_kernel.access({'cm_run_module_uoa':ini['cm_module_uid'],
00068                            'cm_action':'load',
00069                            'cm_data_uoa':ae['cm_data_uoa'],
00070                            'cm_repo_uoa':lwrepo})
00071        if r['cm_return']>0:
00072           if r['cm_return']!=16: return r
00073 
00074           # Create entry
00075           r=cm_kernel.access({'cm_run_module_uoa':ini['cm_module_uid'],
00076                               'cm_action':'add',
00077                               'cm_data_uoa':ae['cm_data_uoa'],
00078                               'cm_array':{},
00079                               'cm_repo_uoa':lwrepo})
00080           if r['cm_return']>0: return r
00081        else:
00082           dae=r['cm_data_obj']['cfg']
00083 
00084     space=i.get('space',{})
00085 
00086     # Check additional scenario parameters
00087     ioi=i.get('original_input',{})
00088 
00089     frm1='#form_'+ini['cm_module_uid']+'_1'
00090     frm2='#form_'+ini['cm_module_uid']+'_2'
00091 
00092     a1={}
00093     r=cm_kernel.access({'cm_run_module_uoa':ini['cfg']['cm_modules']['cm-web'],
00094                         'cm_action':'detect_form_params',
00095                         'cm_array':ioi, 
00096                         'cm_prefix':frm1})
00097     if r['cm_return']>0: return r
00098     cm_form_array1=r['cm_array']
00099 
00100     r=cm_kernel.restore_flattened_array({'cm_array':cm_form_array1, 
00101                                          'cm_replace_in_keys':{'^35^':'#', '^64^':'@'}})
00102     if r['cm_return']>0: return r
00103     a1=r['cm_array']
00104 
00105     ags=a1.get('aggregate_statistics','')
00106     rcn=a1.get('reuse_calibration_number','')
00107 
00108     # Detect data in the forms
00109     a2={}
00110     r=cm_kernel.access({'cm_run_module_uoa':ini['cfg']['cm_modules']['cm-web'],
00111                         'cm_action':'detect_form_params',
00112                         'cm_array':ioi, 
00113                         'cm_prefix':frm2})
00114     if r['cm_return']>0: return r
00115     cm_form_array2=r['cm_array']
00116 
00117     r=cm_kernel.restore_flattened_array({'cm_array':cm_form_array2, 
00118                                          'cm_replace_in_keys':{'^35^':'#', '^64^':'@'}})
00119     if r['cm_return']>0: return r
00120     a2=r['cm_array']
00121 
00122     # Get pipeline module and description
00123     mu=i['caller_module_uid']
00124     r=cm_kernel.get_data_description({'cm_module_uoa':mu})
00125     if r['cm_return']>0: return r
00126     pu=r['cm_data_obj']['cfg']['cm_p_uids']
00127 
00128     # Check if already have first point and if aggregate statistics, take statistical characteristics from it:
00129     repeat=''
00130     if len(space.get('points',[]))>0:
00131        sp=space['points'][0].get('pipeline_output',{}).get('state',{})
00132 
00133        # Take repetition number 
00134        if rcn=='yes':
00135           repeat=sp.get(pu['run_program'], {}).get('input',{}).get('run_vars',{}).get('CT_REPEAT_MAIN','')
00136 
00137        if ags=='yes':
00138           sc=sp.get('cm_stat_characteristics',{})
00139           if len(sc)>0:
00140              state['cm_stat_characteristics']=copy.deepcopy(sc)
00141 
00142     if a1.get('force_repeat_number','')!='':
00143        repeat=a1['force_repeat_number']
00144 
00145     # Start exploration
00146     cm_explore_state=[]
00147     iter=0
00148     start_time=time.time()
00149 
00150     nis=i.get('number_of_iterations','')
00151     ni=0
00152     if nis!='': ni=int(nis)
00153 
00154     # Set seed if needed
00155     if a1.get('random_seed','')!='':
00156        cm_kernel.print_for_con('')
00157        cm_kernel.print_for_con('Setting random seed to '+str(a1['random_seed']))
00158        cm_kernel.print_for_con('')
00159        random.seed(a1['random_seed'])
00160 
00161     finish=False
00162     while not finish:
00163        iter+=1
00164        if ni>0 and iter>ni: break
00165 
00166        #Prepare initial coarse grain choices
00167        cm_kernel.print_for_con('************************************************************************************')
00168        x=''
00169        if ni>0: x=' out of '+str(ni)
00170        cm_kernel.print_for_con('Fine-grain iteration:    '+str(iter)+x)
00171 
00172        t=time.time()-start_time
00173        ts="%.1f" % t
00174        cm_kernel.print_for_con('Time elapsed: '+ts+' sec.')
00175 
00176        cm_kernel.print_for_con('')
00177        cm_kernel.print_for_con('Preparing choices (fine-grain point in multi-dimensional space):')
00178 
00179        if rcn=='yes' and repeat!='':
00180           state[pu['run_program']]['input']['calibrate']='no'
00181           if 'run_vars' not in state[pu['run_program']]['input']: 
00182              state[pu['run_program']]['input']['run_vars']={}
00183           state[pu['run_program']]['input']['run_vars']['CT_REPEAT_MAIN']=repeat
00184 
00185        jj={'cm_run_module_uoa':ini['cfg']['cm_modules']['cm-choice'],
00186            'cm_action':'prepare_choices',
00187            'cm_array':state,
00188            'cm_data_desc':desc,
00189            'cm_explore':i.get('cm_form_explore',{}),
00190            'cm_explore_state':cm_explore_state,
00191            'cm_explore_level':'1'}
00192        r=cm_kernel.access(jj)
00193        if r['cm_return']>0: return r
00194 
00195        if a1.get('continue_indefinitely','')!='yes' and \
00196           r['cm_exploration_finished']=='yes':
00197           if r['cm_last_iteration']=='yes': finish=True
00198           else: break
00199 
00200        cm_explore_state=r['cm_explore_state']
00201 
00202        # Run pipeline
00203        ii={}
00204        ii['cm_run_module_uoa']=ini['cfg']['cm_modules']['ctuning.pipeline.build_and_run_program']
00205        ii['cm_action']='run_stat'
00206        ii['state']=state
00207        ii_copy=copy.deepcopy(ii)
00208        # we may move next 2 after deepcopy to avoid creating too big data ...
00209        ii['desc']=desc # needed for stats ...
00210        ii['additional_params']=a1
00211        r=cm_kernel.access(ii)
00212        if r['cm_return']>0: return r
00213 
00214        statex=r['state']
00215 
00216        if repeat=='':
00217           repeat=statex.get(pu['run_program'], {}).get('input',{}).get('run_vars',{}).get('CT_REPEAT_MAIN','')
00218 
00219        # Append points
00220        if ags=='yes' and len(space.get('points',[]))>0:
00221           space['points'][0]['pipeline_input']=ii_copy
00222           space['points'][0]['pipeline_output']=r
00223        else:
00224           if 'points' not in space: space['points']=[]
00225           space['points'].append({'pipeline_input': ii_copy,
00226                                   'pipeline_output': r})
00227 
00228        # Record in repository
00229        if sr=='yes':
00230           cm_kernel.print_for_con('')
00231           cm_kernel.print_for_con('Recording point in repository ...')
00232 
00233           jj={'cm_run_module_uoa':ini['cm_module_uid'],
00234               'cm_action':'add',
00235               'cm_array':space}
00236 
00237           if aggr=='yes' and len(ae)>0:
00238              cm_kernel.print_for_con('')
00239              cm_kernel.print_for_con('Recording point in aggregated entry '+ae['cm_data_uoa']+' ...')
00240              jj['cm_action']='update'
00241              jj.update(ae)
00242 
00243           jj['cm_repo_uoa']=wrepo
00244 
00245           jj_copy=copy.deepcopy(jj)
00246 
00247           r=cm_kernel.access(jj)
00248           if r['cm_return']>0: return r
00249 
00250           jj=jj_copy
00251           jj['cm_repo_uoa']=lwrepo
00252 
00253           r=cm_kernel.access(jj)
00254           if r['cm_return']>0: return r
00255 
00256           if aggr=='yes' and len(ae)==0:
00257              ae['cm_data_uoa']=r['cm_uid']
00258              ae['cm_module_uoa']=ini['cm_module_uid']
00259              ae['cm_repo_uoa']=wrepo
00260 
00261     return {'cm_return':0}
00262 
00263 # ============================================================================
00264 def prepare_input_params(i):
00265     """
00266     Prepare input parameters for this scenario
00267 
00268     Input:  {
00269               cm_form_array - array with forms
00270               form_exists   - yes or no
00271               cm_array1     - array from form 1 (coarse-grain points)
00272               cm_array2     - array from form 2 (additional parameters) just in case
00273               caller_cfg    - caller module cfg
00274             }
00275 
00276     Output: {
00277               cm_return   - if =0, success
00278             }
00279     """
00280 
00281     # Get array with forms
00282     af=i.get('cm_form_array',{})
00283     frm1='#form_'+ini['cm_module_uid']+'_1'
00284     frm2='#form_'+ini['cm_module_uid']+'_2'
00285     form_exists=i.get('form_exists','')
00286     xa1=i.get('cm_array1',{})
00287     xa2=i.get('cm_array2',{})
00288     cc=i.get('caller_cfg',{})
00289 
00290     # Detect data in the forms
00291     a1={}
00292     r=cm_kernel.access({'cm_run_module_uoa':ini['cfg']['cm_modules']['cm-web'],
00293                         'cm_action':'detect_form_params',
00294                         'cm_array':af, 
00295                         'cm_prefix':frm1})
00296     if r['cm_return']>0: return r
00297     cm_form_array1=r['cm_array']
00298     cm_form_commands1=r['cm_commands']
00299     cm_form_explore1=r['cm_explore']
00300     cm_data_desc1=ini['cfg']['scenario_desc']
00301 
00302     # Detect data in the forms
00303     a2={}
00304     r=cm_kernel.access({'cm_run_module_uoa':ini['cfg']['cm_modules']['cm-web'],
00305                         'cm_action':'detect_form_params',
00306                         'cm_array':af, 
00307                         'cm_prefix':frm2})
00308     if r['cm_return']>0: return r
00309     cm_form_array2=r['cm_array']
00310     cm_form_commands2=r['cm_commands']
00311     cm_form_explore2=r['cm_explore']
00312 
00313     if form_exists=='yes':
00314        r=cm_kernel.restore_flattened_array({'cm_array':cm_form_array1, 
00315                                             'cm_replace_in_keys':{'^35^':'#', '^64^':'@'}})
00316        if r['cm_return']>0: return r
00317        a1=r['cm_array']
00318 
00319        r=cm_kernel.restore_flattened_array({'cm_array':cm_form_array2, 
00320                                             'cm_replace_in_keys':{'^35^':'#', '^64^':'@'}})
00321        if r['cm_return']>0: return r
00322        a2=r['cm_array']
00323 
00324     ii={'cm_run_module_uoa':ini['cfg']['cm_modules']['cm-web'],
00325         'cm_action':'visualize_data',
00326         'cm_array':a1,
00327         'cm_data_desc':cm_data_desc1,
00328         'cm_form_commands':cm_form_commands1,
00329         'cm_form_explore':cm_form_explore1,
00330         'cm_separator':'#',
00331         'cm_separator_form':frm1+'#',
00332         'cm_forms_exists':form_exists,
00333         'cm_support_raw_edit':'no',
00334         'cm_mode':'add',
00335         'hide_add_new_object':'yes',
00336         'cm_explore':'yes'}
00337     r=cm_kernel.access(ii)
00338     if r['cm_return']>0: return r
00339     cm_kernel.print_for_web(r['cm_string'])
00340 
00341     return {'cm_return':0}
00342 
00343 # ============================================================================
00344 def web_view_header(i):
00345     """
00346     Prepare header
00347 
00348     Input:  {
00349               header_desc - header description
00350             }
00351 
00352     Output: {
00353               cm_return   - if =0, success
00354               cm_html     - header html
00355               cm_length   - header length
00356             }
00357     """
00358 
00359     # Get web style
00360     if 'cfg' in cm_kernel.ini['web_style']: web=cm_kernel.ini['web_style']['cfg']
00361     else:
00362        return {'cm_return':1, 'cm_error':'web style is not defined'}
00363 
00364     local_pipeline_desc=ini['cfg'].get('pipeline_point_viewer_desc',{})
00365 
00366     x1=''
00367     if 'table_bgcolor_line5' in web: x1=' bgcolor="'+web['table_bgcolor_line5']+'" ' 
00368     x2=''
00369     if 'table_bgcolor_line6' in web: x2=' bgcolor="'+web['table_bgcolor_line6']+'" '
00370 
00371     vsx=ini['cfg']['pipeline_point_viewer']
00372     vs=vsx.get('main',[])
00373     ks=vsx.get('key_prefix','')
00374 
00375     desc=i.get('header_desc',{})
00376 
00377     h=''
00378 
00379     col=True; 
00380     for kx in vs:
00381         k=ks+kx
00382         ky='#'+kx
00383         v=desc.get(ky,{}).get('desc_text','')
00384         if v=='': v=local_pipeline_desc.get(ky,{}).get('desc_text','')
00385 
00386         if col: col=False ; x=x1
00387         else:   col=True  ; x=x2
00388         
00389         h+='<td align="center"'+x+'><small><b>'+v+':</b></small></td>'
00390 
00391     return {'cm_return':0, 'cm_html':h, 'cm_length':str(len(vs))}
00392 
00393 # ============================================================================
00394 def web_view_data(i):
00395     """
00396     Prepare header
00397 
00398     Input:  {
00399               cm_data        - data object from pipeline
00400               header_desc    - header description
00401               cur_line_style - { 
00402                                  cur    - cur (style1 or style2)
00403                                  style1
00404                                  style2
00405                                }
00406               point          - point to visualize
00407             }
00408 
00409     Output: {
00410               cm_return   - if =0, success
00411               cm_html     - header html
00412             }
00413     """
00414 
00415     # Get web style
00416     if 'cfg' in cm_kernel.ini['web_style']: web=cm_kernel.ini['web_style']['cfg']
00417     else:
00418        return {'cm_return':1, 'cm_error':'web style is not defined'}
00419 
00420     desc=i.get('header_desc',{})
00421 
00422     # Current style
00423     cls=i.get('cur_line_style',{})
00424     y=cls.get('cur','')
00425     y1=cls.get('style1','')
00426     y2=cls.get('style2','')
00427 
00428     # Prepare some vars to change colors for each second line
00429     x1=''
00430     if 'table_bgcolor_line3' in web: x1=' bgcolor="'+web['table_bgcolor_line3']+'" ' 
00431     x2=''
00432     if 'table_bgcolor_line4' in web: x2=' bgcolor="'+web['table_bgcolor_line4']+'" '
00433     x3=''
00434     if 'table_bgcolor_line5' in web: x3=' bgcolor="'+web['table_bgcolor_line5']+'" ' 
00435     x4=''
00436     if 'table_bgcolor_line6' in web: x4=' bgcolor="'+web['table_bgcolor_line6']+'" '
00437 
00438     vsx=ini['cfg']['pipeline_point_viewer']
00439     vs=vsx.get('main',[])
00440     vsf=vsx.get('fail',[])
00441     vss=vsx.get('strange',[])
00442     vsff=vsx.get('full_fail',[])
00443     vnt=vsx.get('normality_test',[])
00444 
00445     ks=vsx.get('key_prefix','')
00446 
00447     d=i.get('cm_data',{})
00448     points=d.get('cm_data_obj',{}).get('cfg',{}).get('points',[])
00449 
00450     h=''
00451 
00452     col=True; 
00453     for kx in vs:
00454 
00455         k=ks+kx
00456 
00457         if col: 
00458            col=False 
00459            if y==y1: x=x1
00460            else: x=x3
00461         else: 
00462            col=True 
00463            if y==y1: x=x2
00464            else: x=x4
00465 
00466         p=points[int(i.get('point','0'))]
00467         rg=cm_kernel.get_value_by_flattened_key({'cm_array':p, 'cm_key':k})
00468         if rg['cm_return']>0: return rg
00469         v=rg['cm_value']
00470         if v==None: v=''
00471 
00472         d1=desc.get('#'+kx,{})
00473         d1['cm_view_as_text']='yes'
00474         ii={'cm_run_module_uoa':ini['cfg']['cm_modules']['cm-web'],
00475             'cm_action':'convert_field_to_html',
00476             'cm_value':str(v),
00477             'cm_key':'',
00478             'cm_mode':'view',
00479             'cm_data_desc':d1,
00480             'cm_disable_coloring':'yes'}
00481         r1=cm_kernel.access(ii)
00482         if r1['cm_return']>0: return r1
00483         vh=r1['cm_value_html']
00484         vt=r1['cm_value_text']
00485 
00486         h+='<td '+x+' align="right" valign="top"><small>'
00487         if kx in vsf:
00488            if v=='' or int(v)!=0:
00489               h+='<span style="color:#9F0000"><B>Fail ('+str(v)+')</B></span>'
00490            else:
00491               h+=str(v)
00492         elif kx in vss:
00493            if v=='' or int(v)!=0:
00494               h+='<span style="color:#9F0000">Strange ('+str(v)+')</span>'
00495            else:
00496               h+=str(v)
00497         elif kx in vsff:
00498            if v=='yes':
00499               h+='<span style="color:#9F0000"><b>Fail</b></span>'
00500            else:
00501               h+='no'
00502         elif kx in vnt:
00503            if v!='' and float(v)<0.05:
00504               h+='<span style="color:#9F0000"><B>'+str(v)+'</B></span>'
00505            else:
00506               h+=str(v)
00507         else:
00508            h+=vh
00509         h+='<BR>\n'
00510         h+='</small></td>'
00511 
00512     return {'cm_return':0, 'cm_html':h}

Generated on Wed May 28 02:49:02 2014 for Collective Mind Framework by DoxyGen 1.6.1
Concept, design and coordination: Grigori Fursin (C) 1993-2013