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 string
00016 import os
00017 import random
00018 import copy
00019 import json
00020 
00021 # ============================================================================
00022 def init(i):
00023     return {'cm_return':0}
00024 
00025 # ============================================================================
00026 def explore(i):
00027 
00028     """
00029     Explore choices
00030 
00031     Input:  {
00032               cm_choices                - TODO: describe format, see ct-compiler gcc-4.6.2
00033               cm_exploration_strategy   - random
00034               (choice_rnd_seed)         - random seed
00035               *concatenate_output)      - if 'yes', concatenate list to string
00036               (output_key)              - use this value to set output key instead of cm_choice.
00037                                           Mainly used for command line exploration.
00038             }
00039 
00040     Output: {
00041               cm_return                        - if =0, success
00042               cm_choice or value of output_key - list of selected choices
00043             }
00044     """
00045 
00046     if 'cm_choices' not in i:
00047        return {'cm_return':1, 'cm_error':'"cm_choices" are not defined'}
00048     if 'cm_exploration_strategy' not in i:
00049        return {'cm_return':1, 'cm_error':'"cm_exploration_strategy" is not defined'}
00050 
00051     output_key='cm_choice'
00052     if 'output_key' in i: output_key=i['output_key']
00053 
00054     choices=i['cm_choices']
00055     choice=[]
00056 
00057     ii={'cm_choices':choices, 
00058         'cm_exploration_strategy':i['cm_exploration_strategy'],
00059         'cm_choice':choice}
00060     if 'choice_rnd_seed' in i: ii['choice_rnd_seed']=i['choice_rnd_seed']
00061 
00062     r=select(ii)
00063 
00064     if r['cm_return']==0:
00065        # Check if concatenate
00066        if i.get('concatenate_output','')=='yes':
00067           s=''
00068           for x in r['cm_choice']:
00069               if i.get('concatenate_output','')=='yes':
00070                  s+=' '+x
00071           r['cm_choice']=s.strip()
00072 
00073        if i.get('cm_console','')=='txt':
00074           if i.get('concatenate_output', '')=='yes': 
00075              cm_kernel.print_for_con(s.strip())
00076           else:
00077              for x in r['cm_choice']:
00078                  cm_kernel.print_for_con(x)
00079 
00080        if 'cm_choice' in r and 'output_key' in i:
00081           rx=cm_kernel.set_value_by_flattened_key({'cm_array':r, 'cm_key':output_key, 'cm_value':r['cm_choice']})
00082           if rx['cm_return']>0: return rx
00083           r=rx['cm_array']
00084           if 'cm_choice' in r: del(r['cm_choice'])
00085 
00086     return r
00087 
00088 # ============================================================================
00089 def select(i):
00090     """
00091     Select from the choice
00092 
00093     Input:  {
00094               cm_choices              - TODO: describe format, see ct-compiler gcc-4.6.2
00095               cm_exploration_strategy - random
00096               (choice_rnd_seed)       - random seed
00097               (cm_choice)             - previous cm_choice state (can be updated using various methods including probabilistic)
00098             }
00099 
00100     Output: {
00101               cm_return - return code = 0, if successful
00102               cm_choice
00103             }
00104     """
00105 
00106     if 'cm_choices' not in i:
00107        return {'cm_return':1, 'cm_error':'"cm_choices" are not defined'}
00108     if 'cm_exploration_strategy' not in i:
00109        return {'cm_return':1, 'cm_error':'"cm_exploration_strategy" is not defined'}
00110 
00111     choices=i['cm_choices']
00112     choice=[]
00113     if 'cm_choice' in i: choice=i['cm_choice']
00114     es=i['cm_exploration_strategy']
00115 
00116     if 'choice_rnd_seed' in i:
00117        random.seed(int(i['choice_rnd_seed']))
00118 
00119     if 'cm_choice' in choices and choices['cm_choice']=='true':
00120        if es=='random':
00121           cm_prefix=''
00122           if 'cm_prefix' in choices: cm_prefix=choices['cm_prefix']
00123           if choices['cm_type']=='combine_without_order':
00124              # Select random length!
00125 
00126              ln=random.randrange(0, len(choices['cm_list']))
00127              choice1=[]
00128              for z in range(0, ln):
00129                  y=random.randrange(0, len(choices['cm_list'])-1)
00130                  while y in choice1:
00131                        y=random.randrange(0, len(choices['cm_list'])-1)
00132                  choice1.append(y)
00133 
00134                  x=choices['cm_list'][y]
00135                  if type(x) is dict and 'cm_choice' in x and x['cm_choice']=='true':
00136                     r=select({'cm_choices':x, 
00137                               'cm_exploration_strategy':i['cm_exploration_strategy'],
00138                               'cm_choice':choice})
00139                     if r['cm_return']>0: return r
00140                  else:
00141                     choice.append(cm_prefix+x)
00142 
00143 #             for x in choices['cm_list']:
00144 #                 y=random.randrange(0,2)
00145 #                 if y==0: 
00146 #                    if type(x) is dict and 'cm_choice' in x and x['cm_choice']=='true':
00147 #                       r=select({'cm_choices':x, 
00148 #                                 'cm_exploration_strategy':i['cm_exploration_strategy'],
00149 #                                 'cm_choice':choice})
00150 #                       if r['cm_return']>0: return r
00151 #                    else:
00152 #                       choice.append(cm_prefix+x)
00153           elif choices['cm_type']=='combine_with_order':
00154              for x in choices['cm_list']:
00155                  y=random.randrange(0,2)
00156                  if y==0: 
00157                     if type(x) is dict and 'cm_choice' in x and x['cm_choice']=='true':
00158                        r=select({'cm_choices':x, 
00159                                  'cm_exploration_strategy':i['cm_exploration_strategy'],
00160                                  'cm_choice':choice})
00161                        if r['cm_return']>0: return r
00162                     else:
00163                        choice.append(cm_prefix+x)
00164           elif choices['cm_type']=='select_all':
00165              for x in choices['cm_list']:
00166                  if type(x) is dict and 'cm_choice' in x and x['cm_choice']=='true':
00167                     r=select({'cm_choices':x, 
00168                               'cm_exploration_strategy':i['cm_exploration_strategy'],
00169                               'cm_choice':choice})
00170                     if r['cm_return']>0: return r
00171                  else:
00172                     choice.append(cm_prefix+x)
00173           elif choices['cm_type']=='one_of':
00174                list=choices['cm_list']
00175                y=random.randrange(0,len(list))
00176                x=list[y]
00177                if type(x) is dict and 'cm_choice' in x and x['cm_choice']=='true':
00178                   r=select({'cm_choices':x, 
00179                             'cm_exploration_strategy':i['cm_exploration_strategy'],
00180                             'cm_choice':choice})
00181                   if r['cm_return']>0: return r
00182                else:
00183                   choice.append(cm_prefix+x)
00184           elif choices['cm_type']=='range':
00185                r1=int(choices['cm_range_start'])
00186                r2=int(choices['cm_range_stop'])
00187                rs=int(choices['cm_range_step'])
00188                rx=(r2-r1+1)/rs
00189                y=random.randrange(0,rx)
00190                choice.append(cm_prefix+str(r1+(y*rs)))
00191        else:
00192            return {'cm_return':1, 'cm_error':'choice type "'+es+'"is not recognized'}
00193 
00194     return {'cm_return':0, 'cm_choice':choice}
00195 
00196 # ============================================================================
00197 def prepare_tuning_dimension_for_web(i):
00198 
00199     """
00200     Prepare tuning dimension for web
00201 
00202     Input:  {
00203               key1 
00204               key2 
00205               key_ext
00206               form_name
00207               form_explore
00208               cm_data_desc - data description
00209             }
00210 
00211     Output: {
00212               cm_return  - if =0, success
00213               cm_string  - html for choices, explore strategy and tuning parameters
00214             }
00215     """
00216     key1=i.get('key1','')
00217     key2=i.get('key2','')
00218     key_ext=i.get('key_ext','')
00219     form_name=i.get('form_name','')
00220     form_explore=i.get('form_explore',{})
00221     d=i.get('cm_data_desc',{})
00222     t=d.get('type','')
00223 
00224     s='<TD><B><center>Explore<BR>choices:</center></b></TD><TD>'
00225 
00226     v1=''
00227     vstart=''
00228     vstop=''
00229     vstep=''
00230     if key1 in form_explore:
00231        v1=form_explore[key1].get('type','')
00232        vstart=form_explore[key1].get('start','')
00233        vstop=form_explore[key1].get('stop','')
00234        vstep=form_explore[key1].get('step','')
00235 
00236     if v1=='': v1=d.get('explore_type','')
00237     if vstart=='': vstart=d.get('explore_start','')
00238     if vstop=='': vstop=d.get('explore_stop','')
00239     if vstep=='': vstep=d.get('explore_step','')
00240 
00241     s+='<select class="cm-select" style="width:170px" name="@explore_type@'+key2+'"'+key_ext+'>\n'
00242 #       ' onchange="document.'+form_name+'.submit();">\n'
00243 
00244     for xx in ini['cfg']['cm_explore_types']:
00245         yy=xx.keys()[0]
00246         x=xx[yy]
00247 
00248         z=''
00249         if yy==v1: z=' SELECTED '
00250 
00251         s+='<option value="'+yy+'"'+z+'>'+x+'</option>\n'
00252     s+='</TD>'
00253 
00254     if d.get('has_choice','')!='yes' and (t=='integer' or t=='float'):
00255        s+='<TD><B><center>Start:</center></b></TD><TD>'
00256        s+='<input type="text" size="7" spellcheck="false" name="@explore_start@'+key2+'"'+key_ext+' value="'+vstart+'"></TD>'
00257 
00258        s+='<TD><B><center>Stop:</center></b></TD><TD>'
00259        s+='<input type="text" size="7" spellcheck="false" name="@explore_stop@'+key2+'"'+key_ext+' value="'+vstop+'"></TD>'
00260 
00261        s+='<TD><B><center>Step:</center></b></TD><TD>'
00262        s+='<input type="text" size="7" spellcheck="false" name="@explore_step@'+key2+'"'+key_ext+' value="'+vstep+'"></TD>'
00263 
00264     return {'cm_return':0, 'cm_string':s}
00265 
00266 # ============================================================================
00267 def prepare_choices(i):
00268 
00269     """
00270     Prepare tuning dimension
00271 
00272     Input:  {
00273               cm_array         - pipeline array
00274               cm_data_desc     - pipeline data description
00275               cm_explore       - exploration parameters 
00276               cm_explore_state - exploration state
00277               cm_explore_level - exploration level ('' - coarse-grain, '1' - next level, ...)
00278               random_seed      - random seed
00279             }
00280 
00281     Output: {
00282               cm_return               - if =0, success
00283               cm_explore_state        - exploration state
00284               cm_exploration_finished - if 'yes', exploration finished (for nested loops)
00285             }
00286     """
00287 
00288     a=i.get('cm_array',{})
00289     d=i.get('cm_data_desc',{})
00290     de=i.get('cm_explore',{})
00291 
00292     if i.get('random_seed','')!='': random.seed(int(i['random_seed']))
00293 
00294     # FGG: Need to save data description otherwise choices created at run-time for different dimensions 
00295     #  mix up/slow down logic - it's not a problem but should be cleaned up/optimized one day
00296     d_copy=copy.deepcopy(d)
00297 
00298     # Get initial state with dimensions and choices
00299     e=i.get('cm_explore_state',[])
00300     init=False
00301     if len(e)==0:
00302        # Init state
00303        init=True
00304        ii={'cm_run_module_uoa':ini['cfg']['cm_modules']['cm-web'],
00305            'cm_action':'visualize_data',
00306            'cm_array':a,
00307            'cm_data_desc':d,
00308            'cm_form_explore':de,
00309            'cm_separator':'#',
00310            'cm_mode':'add',
00311            'cm_explore':'yes',
00312            'cm_explore_state':e,
00313            'cm_explore_level':i.get('cm_explore_level','')}
00314        r=cm_kernel.access(ii)
00315        if r['cm_return']>0: return r
00316 
00317        e=r['cm_explore_state']
00318 
00319     # Iteratively prepare pipeline (each time expanding dependant dimensions)
00320     ef='no'
00321     li='no'
00322     l=len(e)
00323 
00324     # Check nested loops from highest to lowest
00325     loop_finished=False
00326     has_random=False
00327     has_loop=False
00328     other_loop_reset=False
00329     for t in range(16,0,-1):
00330         # Scan to check that there is a loop
00331         loop='loop_'+str(t)
00332         found_loop=False
00333 
00334         for n in e:
00335             if n.get('type','')==loop:
00336                found_loop=True
00337                break
00338 
00339         if found_loop or t==1:
00340            cm_kernel.print_for_con('')
00341            if found_loop: 
00342                cm_kernel.print_for_con('Processing nested loop: '+str(t))
00343                cm_kernel.print_for_con('')
00344 
00345            for j in range(0,l):
00346                n=e[j]
00347 
00348                # Prepare some vars
00349                desc=n.get('desc',{})
00350                dt=desc.get('type','')
00351 
00352                x=n.get('index','')
00353                t=n.get('type','')
00354                v=n.get('value','')
00355                c=n.get('choice',[])
00356 
00357                vstart=n.get('start','')
00358                vstop=n.get('stop','')
00359                vstep=n.get('step','')
00360                if vstart=='': vstart='0'
00361                if vstop=='': vstop='0'
00362                if vstep=='': vstep='0'
00363 
00364                if dt=='uoa' or len(c)>0 or desc.get('has_choice','')=='yes': 
00365                   isc=True
00366                else:
00367                   isc=False
00368                   if dt=='integer':
00369                      rstart=int(vstart)
00370                      rstop=int(vstop)
00371                      rstep=int(vstep)
00372                   else:
00373                      rstart=float(vstart)
00374                      rstop=float(vstop)
00375                      rstep=float(vstep)
00376 
00377                h=''
00378 
00379                # Prepare according exploration type
00380                if t=='disabled':
00381                   v=''
00382                   h=' (disabled)'
00383                elif t=='fixed':
00384                   # in some cases we fix empty selection (dataset depending on program)
00385                   # if v=='': return {'cm_return':1, 'cm_error':'dimension '+x+' is fixed, but value is not set'}
00386                   h=' (fixed)'
00387                elif t=='fixed_first':
00388                   if isc:
00389                      v=''
00390                      if len(c)>0: v=c[0]
00391                   h=' (fixed first)'
00392                elif t=='random':
00393                   # first check if enable or disable
00394                   u=int(random.randint(0,1))
00395                   if n.get('desc',{}).get('forbid_disable_at_random','')=='yes' or u==0:
00396                      has_random=True
00397                      v=''
00398                      if isc:
00399                         if len(c)>0: 
00400                            if len(c)==1: v=c[0]
00401                            else: v=c[random.randint(0, len(c)-1)]
00402                         h=' (randomly selected from range {'+str(len(c))+'})'
00403                      else:
00404                         rx=(rstop-rstart)/rstep
00405                         y=random.randint(0,rx)
00406                         v=str(rstart+(y*rstep))
00407                         h=' (randomly selected from range {'+str(rstart)+', '+str(rstop)+', '+str(rstep)+'})'
00408                   else:
00409                      v=''
00410                      h=' (randomly disabled)'
00411 
00412                elif t.startswith('loop_'):
00413                   has_loop=True
00414                   if init:
00415                      v=''
00416                      if isc:
00417                         if len(c)>0: v=c[0]
00418                      else:
00419                         v=str(rstart)
00420                      h=' (loop initialized)'
00421                   else:
00422                      if other_loop_reset:
00423                         v=''
00424                         if isc:
00425                            if len(c)>0: v=c[0]
00426                         else:
00427                            v=str(rstart)
00428                         h=' (loop reset)'
00429                      elif t==loop:
00430                         if isc:
00431                            if len(c)>0:
00432                               index=c.index(v)
00433                               index+=1
00434                               if index<len(c): 
00435                                  v=c[index]
00436                                  if loop_finished:
00437                                     loop_finished=False
00438                                     other_loop_reset=True
00439                                  h=' (loop iterated)'
00440                               else: 
00441                                  v=c[0]
00442                                  loop_finished=True
00443                                  h=' (loop finished)'
00444                            else: 
00445                               v=''
00446                               loop_finished=True
00447                               h=' (loop finished)'
00448                         else:
00449                            if dt=='integer':
00450                               vv=int(v)
00451                            else:
00452                               vv=float(v)
00453                            vv+=rstep
00454                            if vv<=rstop:
00455                               if loop_finished:
00456                                  loop_finished=False
00457                                  other_loop_reset=True
00458                               h=' (loop iterated)'
00459                            else: 
00460                               vv=rstart
00461                               loop_finished=True
00462                               h=' (loop finished)'
00463                            v=str(vv)
00464                            
00465                else:
00466                   h=' (exploration type empty or unknown - skipping)'
00467                   continue
00468 
00469                cm_kernel.print_for_con('Dimension: '+x+' = '+v+h)
00470 
00471                # Set value
00472                ro=cm_kernel.set_value_by_flattened_key({'cm_array':a,
00473                                                         'cm_key':x,
00474                                                         'cm_value':v})
00475                if ro['cm_return']>0: return ro
00476 
00477                # Refresh pipeline if needed
00478                if desc.get('skip_form_refresh','')=='yes':
00479                   e[j]['value']=v
00480                else:
00481                   e1=[]
00482                   ii={'cm_run_module_uoa':ini['cfg']['cm_modules']['cm-web'],
00483                       'cm_action':'visualize_data',
00484                       'cm_array':a,
00485                       'cm_data_desc':d,
00486                       'cm_form_explore':de,
00487                       'cm_separator':'#',
00488                       'cm_mode':'add',
00489                       'cm_forms_exists':'yes',
00490                       'cm_explore':'yes',
00491                       'cm_explore_state':e1,
00492                       'cm_explore_level':i.get('cm_explore_level','')}
00493                   r=cm_kernel.access(ii)
00494                   if r['cm_return']>0: return r
00495 
00496                   e1=r['cm_explore_state']
00497 
00498                   # Get value (after pipeline refresh)
00499                   ro=cm_kernel.get_value_by_flattened_key({'cm_array':a,
00500                                                            'cm_key':x})
00501                   if ro['cm_return']>0: return ro
00502                   e[j]['value']=ro['cm_value']
00503 
00504                   # Update dependent choices
00505                   for g in range(j+1, l):
00506                       e[g]['choice']=e1[g]['choice']
00507 
00508                   d=copy.deepcopy(d_copy)
00509 
00510         if found_loop and not loop_finished: break
00511 
00512 
00513     if loop_finished or (not has_loop and not has_random):
00514        cm_kernel.print_for_con('')
00515 
00516        ef='yes'
00517        if (not has_loop and not has_random): 
00518           li='yes'
00519           cm_kernel.print_for_con('One fixed point in space during exploration!')
00520        else:
00521           cm_kernel.print_for_con('Exploration finished!')
00522 
00523     return {'cm_return':0, 'cm_explore_state':e, 'cm_exploration_finished':ef, 'cm_last_iteration':li}

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