Changeset 168


Ignore:
Timestamp:
03/11/14 14:45:29 (10 years ago)
Author:
sz
Message:

reformatting

Location:
cpp/frams/genetics
Files:
4 edited

Legend:

Unmodified
Added
Removed
  • cpp/frams/genetics/f9/conv_f9.cpp

    r157 r168  
    1313{
    1414        name = "Turtle3D-ortho encoding";
    15         in_format  = '9';
     15        in_format = '9';
    1616        out_format = '0';
    1717        mapsupport = 0; //would be easy and nice to add!
     
    1919
    2020
    21 const char* turtle_commands_f9 ="LRDUBF";
     21const char* turtle_commands_f9 = "LRDUBF";
    2222
    2323//const char* turtle_commandsX_f9="-+0000";
     
    3131        Model m;
    3232        m.open();
    33         int recently_added=addSegment(m,vertices,current,0xDead);
    34         for(int i=0;i<in.len();i++)
     33        int recently_added = addSegment(m, vertices, current, 0xDead);
     34        for (int i = 0; i < in.len(); i++)
    3535        {
    36                 char command=in[i];
    37                 char *ptr=strchr((char*)turtle_commands_f9,command);
     36                char command = in[i];
     37                char *ptr = strchr((char*)turtle_commands_f9, command);
    3838                if (ptr)
    3939                {
    40                         int delta[]={0,0,0};
    41                         int pos=ptr-turtle_commands_f9;
    42                         int axis=pos/2;
    43                         int dir=pos%2;
    44                         (*(delta+axis))+=dir*2-1; //+1 or -1 in the given axis
     40                        int delta[] = { 0, 0, 0 };
     41                        int pos = ptr - turtle_commands_f9;
     42                        int axis = pos / 2;
     43                        int dir = pos % 2;
     44                        (*(delta + axis)) += dir * 2 - 1; //+1 or -1 in the given axis
    4545                        current.add(delta);
    46                         recently_added=addSegment(m,vertices,current,recently_added);
     46                        recently_added = addSegment(m, vertices, current, recently_added);
    4747                }
    4848        }
     
    5757}
    5858
    59 int GenoConv_f90::addSegment(Model &m,vector<XYZ_LOC> &vertices,const XYZ_LOC &new_vertex,int recently_added)
     59int GenoConv_f90::addSegment(Model &m, vector<XYZ_LOC> &vertices, const XYZ_LOC &new_vertex, int recently_added)
    6060{
    61         if (vertices.size()<1) //empty model?
     61        if (vertices.size() < 1) //empty model?
    6262        {
    63                 return addNewVertex(m,vertices,new_vertex);
    64         } else
     63                return addNewVertex(m, vertices, new_vertex);
     64        }
     65        else
    6566        {
    66                 int vertex_here=findVertexAt(vertices,new_vertex);
    67                 if (vertex_here<0) //need to create a new Part
     67                int vertex_here = findVertexAt(vertices, new_vertex);
     68                if (vertex_here < 0) //need to create a new Part
    6869                {
    69                         vertex_here=addNewVertex(m,vertices,new_vertex);
     70                        vertex_here = addNewVertex(m, vertices, new_vertex);
    7071                } //else there already exists a Part in new_vertex; new Joint may or may not be needed
    71                 Part *p1=m.getPart(recently_added);
    72                 Part *p2=m.getPart(vertex_here);
    73                 if (m.findJoint(p1,p2)<0 && m.findJoint(p2,p1)<0) //new Joint needed? should always be true if we just created a new Part (vertex_here was <0)
     72                Part *p1 = m.getPart(recently_added);
     73                Part *p2 = m.getPart(vertex_here);
     74                if (m.findJoint(p1, p2) < 0 && m.findJoint(p2, p1) < 0) //new Joint needed? should always be true if we just created a new Part (vertex_here was <0)
    7475                {
    75                         m.addNewJoint(p1,p2);
     76                        m.addNewJoint(p1, p2);
    7677                }
    7778                return vertex_here;
     
    7980}
    8081
    81 int GenoConv_f90::findVertexAt(vector<XYZ_LOC> &vertices,const XYZ_LOC &vertex)
     82int GenoConv_f90::findVertexAt(vector<XYZ_LOC> &vertices, const XYZ_LOC &vertex)
    8283{
    83         for(int i=0;i<vertices.size();i++)
     84        for (int i = 0; i < vertices.size(); i++)
    8485                if (vertices[i].same_coordinates(vertex)) return i;
    8586        return -1;
     
    8788
    8889
    89 int GenoConv_f90::addNewVertex(Model &m,vector<XYZ_LOC> &vertices,const XYZ_LOC &new_vertex)
     90int GenoConv_f90::addNewVertex(Model &m, vector<XYZ_LOC> &vertices, const XYZ_LOC &new_vertex)
    9091{
    91         Part *p=new Part;
    92         p->p.x=new_vertex.x;
    93         p->p.y=new_vertex.y;
    94         p->p.z=new_vertex.z;
     92        Part *p = new Part;
     93        p->p.x = new_vertex.x;
     94        p->p.y = new_vertex.y;
     95        p->p.z = new_vertex.z;
    9596        m.addPart(p);
    9697
    9798        vertices.push_back(new_vertex);
    98         return vertices.size()-1;
     99        return vertices.size() - 1;
    99100}
    100101
    101 double mix(int *colortab,int maxind,double ind)
     102double mix(int *colortab, int maxind, double ind)
    102103{
    103         int indpre=(int)ind;
    104         int indpost=indpre+1;
    105         if (indpost>maxind) indpost=maxind;
    106         int v1=colortab[indpre];
    107         int v2=colortab[indpost];
    108         double d1=ind-indpre;
    109         double d2=indpost-ind;
    110         double v=indpre==indpost?v1:d2*v1+d1*v2; //d1+d2==1
     104        int indpre = (int)ind;
     105        int indpost = indpre + 1;
     106        if (indpost > maxind) indpost = maxind;
     107        int v1 = colortab[indpre];
     108        int v2 = colortab[indpost];
     109        double d1 = ind - indpre;
     110        double d2 = indpost - ind;
     111        double v = indpre == indpost ? v1 : d2*v1 + d1*v2; //d1+d2==1
    111112        return v;
    112113}
     
    115116{
    116117        //a rainbow on Joints: from the first one red, through middle green, to blue or violet - last
    117         static int r[]={1,1,0,0,0,1};
    118         static int g[]={0,1,1,1,0,0};
    119         static int b[]={0,0,0,1,1,1};
    120         int maxind=ARRAY_LENGTH(r)-1;
     118        static int r[] = { 1, 1, 0, 0, 0, 1 };
     119        static int g[] = { 0, 1, 1, 1, 0, 0 };
     120        static int b[] = { 0, 0, 0, 1, 1, 1 };
     121        int maxind = ARRAY_LENGTH(r) - 1;
    121122
    122         int joints_count=m.getJointCount();
    123         for(int i=0;i<joints_count;i++)
     123        int joints_count = m.getJointCount();
     124        for (int i = 0; i < joints_count; i++)
    124125        {
    125                 Joint *j=m.getJoint(i);
    126                 double x=joints_count<2?0:(double)i/(joints_count-1); //0..1, postion in the rainbow
    127                 double ind=x*maxind;
    128                 j->vcolor.x=mix(r,maxind,ind);
    129                 j->vcolor.y=mix(g,maxind,ind);
    130                 j->vcolor.z=mix(b,maxind,ind);
     126                Joint *j = m.getJoint(i);
     127                double x = joints_count < 2 ? 0 : (double)i / (joints_count - 1); //0..1, postion in the rainbow
     128                double ind = x*maxind;
     129                j->vcolor.x = mix(r, maxind, ind);
     130                j->vcolor.y = mix(g, maxind, ind);
     131                j->vcolor.z = mix(b, maxind, ind);
    131132        }
    132133
    133         int parts_count=m.getPartCount();
     134        int parts_count = m.getPartCount();
    134135        SList jlist;
    135         for(int i=0;i<parts_count;i++)
     136        for (int i = 0; i<parts_count; i++)
    136137        {
    137                 Part *p=m.getPart(i);
     138                Part *p = m.getPart(i);
    138139                jlist.clear();
    139                 int count=m.findJoints(jlist,p);
    140                 Pt3D averagecolor(0,0,0); //Parts will get averaged colors from all attached Joints
    141                 FOREACH(Joint*,j,jlist)
    142                         averagecolor+=j->vcolor;
    143                 if (count>5) count=5; //avoid too fat...
    144                 p->vsize=0.3+count/15.0; //the more Joints is attached to a Part, the fatter it is
    145                 p->vcolor=averagecolor/count;
     140                int count = m.findJoints(jlist, p);
     141                Pt3D averagecolor(0, 0, 0); //Parts will get averaged colors from all attached Joints
     142                FOREACH(Joint*, j, jlist)
     143                        averagecolor += j->vcolor;
     144                p->vcolor = averagecolor / count;
     145                if (count>5) count = 5; //avoid too fat...
     146                p->vsize = 0.3 + count / 15.0; //the more Joints is attached to a Part, the fatter it is
    146147        }
    147148}
     
    149150void GenoConv_f90::perturbPartLocations(Model &m) //deterministic "body noise", see APPLY_DETERMINISTIC_BODY_NOISE
    150151{
    151         for(int i=0;i<m.getPartCount();i++)
     152        for (int i = 0; i < m.getPartCount(); i++)
    152153        {
    153                 Part *p=m.getPart(i);
     154                Part *p = m.getPart(i);
    154155                Pt3D noise(
    155                         ((i+1)  %10)-4.5  ,
    156                         ((3*i+5)%10)-4.5  ,
    157                         ((7*i+2)%10)-4.5
     156                        ((i + 1) % 10) - 4.5,
     157                        ((3 * i + 5) % 10) - 4.5,
     158                        ((7 * i + 2) % 10) - 4.5
    158159                        ); //-4.5 .. 4.5 in each axis
    159                 p->p+=noise/1000;
     160                p->p += noise / 1000;
    160161        }
    161162}
  • cpp/frams/genetics/f9/oper_f9.cpp

    r145 r168  
    99
    1010#define FIELDSTRUCT GenoOper_f9
    11 static ParamEntry GENOf9param_tab[]=
     11static ParamEntry GENOf9param_tab[] =
    1212{
    13         {"Genetics: f9",1,1,},
    14         {"f9_mut",0,0,"Mutation probability","f 0 1 0.1",FIELD(mut_prob),"How many genes should be mutated during single mutation (1=all genes, 0.1=ten percent)",},
    15         {0,},
     13        { "Genetics: f9", 1, 1, },
     14        { "f9_mut", 0, 0, "Mutation probability", "f 0 1 0.1", FIELD(mut_prob), "How many genes should be mutated during single mutation (1=all genes, 0.1=ten percent)", },
     15        { 0, },
    1616};
    1717#undef FIELDSTRUCT
     
    2323        par.select(this);
    2424        par.setDefault();
    25         supported_format='9';
     25        supported_format = '9';
    2626}
    2727
     
    2929{
    3030        if (!gene[0]) return 1; //empty is not valid
    31         bool ok=true;
     31        bool ok = true;
    3232        int i;
    33         for(i=0;i<strlen(gene);i++) if (!strchr(turtle_commands_f9,gene[i])) {ok=false; break;}
    34         return ok ? GENOPER_OK : i+1;
     33        for (i = 0; i < strlen(gene); i++) if (!strchr(turtle_commands_f9, gene[i])) { ok = false; break; }
     34        return ok ? GENOPER_OK : i + 1;
    3535}
    3636
     
    3939{
    4040        SString validated; //new genotype (everything except turtle_commands_f9 is skipped)
    41         for(int i=0;i<strlen(gene);i++)
    42                 if (strchr(turtle_commands_f9,gene[i])) validated+=gene[i];  //validated contains only turtle_commands_f9
     41        for (int i = 0; i < strlen(gene); i++)
     42                if (strchr(turtle_commands_f9, gene[i])) validated += gene[i];  //validated contains only turtle_commands_f9
    4343        free(gene);
    44         gene=strdup(validated); //reallocate
     44        gene = strdup(validated); //reallocate
    4545        return GENOPER_OK;
    4646}
    4747
    4848///Very simple mutation
    49 int GenoOper_f9::mutate(char *&gene,float &chg,int &method)
     49int GenoOper_f9::mutate(char *&gene, float &chg, int &method)
    5050{
    51         method=0;
    52         int changes=0,len=strlen(gene);
    53         int symbols=strlen(turtle_commands_f9);
     51        method = 0;
     52        int changes = 0, len = strlen(gene);
     53        int symbols = strlen(turtle_commands_f9);
    5454
    55         for(int i=0;i<len;i++)
     55        for (int i = 0; i < len; i++)
    5656        {
    57                 if (rnd01<mut_prob) //normalize prob with the length of the genotype
     57                if (rnd01 < mut_prob) //normalize prob with the length of the genotype
    5858                {
    59                         char oldgene=gene[i];
    60                         gene[i]=turtle_commands_f9[randomN(symbols)];
    61                         if (gene[i]!=oldgene) changes++;
     59                        char oldgene = gene[i];
     60                        gene[i] = turtle_commands_f9[randomN(symbols)];
     61                        if (gene[i] != oldgene) changes++;
    6262                }
    6363        }
    6464
    65         if (rnd01<mut_prob) //add or delete a random char
     65        if (rnd01 < mut_prob) //add or delete a random char
    6666        {
    6767                SString newgeno(gene);
    68                 if (randomN(2)==0) //add
     68                if (randomN(2) == 0) //add
    6969                {
    70                         int symbols=strlen(turtle_commands_f9);
    71                         int p=randomN(len+1);  //random location
     70                        int symbols = strlen(turtle_commands_f9);
     71                        int p = randomN(len + 1);  //random location
    7272                        //printf("before add: %s\n",(const char*)newgeno);
    73                         newgeno=newgeno.substr(0,p)+SString(turtle_commands_f9+randomN(symbols),1)+newgeno.substr(p);
     73                        newgeno = newgeno.substr(0, p) + SString(turtle_commands_f9 + randomN(symbols), 1) + newgeno.substr(p);
    7474                        //printf("after add: %s\n",(const char*)newgeno);
    7575                        changes++;
    76                 } else if (len>1) //delete
     76                }
     77                else if (len > 1) //delete
    7778                {
    78                         int p=randomN(len);  //random location
     79                        int p = randomN(len);  //random location
    7980                        //printf("before delete: %s\n",(const char*)newgeno);
    80                         newgeno=newgeno.substr(0,p)+newgeno.substr(p+1);
     81                        newgeno = newgeno.substr(0, p) + newgeno.substr(p + 1);
    8182                        //printf("after delete: %s\n",(const char*)newgeno);
    8283                        changes++;
    8384                }
    8485                free(gene);
    85                 gene=strdup(newgeno); //reallocate
     86                gene = strdup(newgeno); //reallocate
    8687        }
    8788
    88         chg=(float)changes/len;
    89         return changes>0?GENOPER_OK:GENOPER_OPFAIL; //no changes => OPFAIL so that genman will call mutate again
     89        chg = (float)changes / len;
     90        return changes > 0 ? GENOPER_OK : GENOPER_OPFAIL; //no changes => OPFAIL so that GenMan will call mutate again
    9091}
    9192
    9293///A simple one-point crossover
    93 int GenoOper_f9::crossOver(char *&g1,char *&g2,float& chg1,float& chg2)
     94int GenoOper_f9::crossOver(char *&g1, char *&g2, float& chg1, float& chg2)
    9495{
    95         int len1=strlen(g1),len2=strlen(g2);
    96         int p1=randomN(len1);  //random cut point for first genotype
    97         int p2=randomN(len2);  //random cut point for second genotype
    98         char *child1=(char*)malloc(p1+len2-p2+1);
    99         char *child2=(char*)malloc(p2+len1-p1+1);
    100         strncpy(child1,g1,p1);   strcpy(child1+p1,g2+p2);
    101         strncpy(child2,g2,p2);   strcpy(child2+p2,g1+p1);
    102         free(g1); g1=child1;
    103         free(g2); g2=child2;
    104         chg1=(float)p1/strlen(child1);
    105         chg2=(float)p2/strlen(child2);
     96        int len1 = strlen(g1), len2 = strlen(g2);
     97        int p1 = randomN(len1);  //random cut point for first genotype
     98        int p2 = randomN(len2);  //random cut point for second genotype
     99        char *child1 = (char*)malloc(p1 + len2 - p2 + 1);
     100        char *child2 = (char*)malloc(p2 + len1 - p1 + 1);
     101        strncpy(child1, g1, p1);   strcpy(child1 + p1, g2 + p2);
     102        strncpy(child2, g2, p2);   strcpy(child2 + p2, g1 + p1);
     103        free(g1); g1 = child1;
     104        free(g2); g2 = child2;
     105        chg1 = (float)p1 / strlen(child1);
     106        chg2 = (float)p2 / strlen(child2);
    106107        return GENOPER_OK;
    107108}
     
    110111unsigned long GenoOper_f9::style(const char *g, int pos)
    111112{
    112         char ch=g[pos];
    113         unsigned long style=GENSTYLE_CS(0,GENSTYLE_INVALID); //default, should be changed below
    114         char *ptr=strchr((char*)turtle_commands_f9,ch);
     113        char ch = g[pos];
     114        unsigned long style = GENSTYLE_CS(0, GENSTYLE_INVALID); //default, should be changed below
     115        char *ptr = strchr((char*)turtle_commands_f9, ch);
    115116        if (ptr)
    116117        {
    117                 int pos=ptr-turtle_commands_f9;
    118                 int axis=pos/2;
    119                 style=GENSTYLE_RGBS(axis==0?200:0,axis==1?200:0,axis==2?200:0,GENSTYLE_NONE);
     118                int pos = ptr - turtle_commands_f9;
     119                int axis = pos / 2;
     120                style = GENSTYLE_RGBS(axis == 0 ? 200 : 0, axis == 1 ? 200 : 0, axis == 2 ? 200 : 0, GENSTYLE_NONE);
    120121        }
    121122        return style;
  • cpp/frams/genetics/genman.cpp

    r145 r168  
    227227Geno GenMan::Validate(const Geno& geny)
    228228{
    229         char format=geny.getFormat();
    230         GenoOperators *gf=getOper_f(format);
    231         if (gf==NULL)
    232                 return Geno(SString::empty(),-1,SString::empty(),SString::sprintf("GENOPER_NOOPER: Validate(): don't know how to handle genetic format %c",format));
    233         char *g2=strdup(geny.getGene()); //copy for validation
    234         int res=gf->validate(g2);
    235         SString sg2=g2;
     229        char format = geny.getFormat();
     230        GenoOperators *gf = getOper_f(format);
     231        if (gf == NULL)
     232                return Geno(SString::empty(), -1, SString::empty(), SString::sprintf("GENOPER_NOOPER: Validate(): don't know how to handle genetic format %c", format));
     233        char *g2 = strdup(geny.getGene()); //copy for validation
     234        int res = gf->validate(g2);
     235        SString sg2 = g2;
    236236        free(g2);
    237         if (res==GENOPER_OK)
    238                 return Geno(sg2,format,geny.getName(),geny.getComment());
     237        if (res == GENOPER_OK)
     238                return Geno(sg2, format, geny.getName(), geny.getComment());
    239239        else
    240                 return Geno(SString::empty(),-1,SString::empty(),SString::sprintf("GENOPER_NOOPER: validate() for format %c returned invalid value",format));
     240                return Geno(SString::empty(), -1, SString::empty(), SString::sprintf("GENOPER_NOOPER: validate() for format %c returned invalid value", format));
    241241}
    242242
     
    245245        float chg; //how many changes
    246246        int method; //mutation method
    247         char format=g.getFormat();
    248         GenoOperators *gf=getOper_f(format);
    249         if (gf==NULL)
    250                 return Geno(SString::empty(),-1,SString::empty(),SString::sprintf("GENOPER_NOOPER: Mutate(): don't know how to handle genetic format %c",format));
    251         Geno gv=g;
    252         bool canvalidate=true;
    253         if (testValidity(gv,canvalidate)>0 && canvalidate==false)
    254                 return Geno("",-1,"","GENOPER_OPFAIL: Mutate(): cannot validate invalid source genotype");
    255         bool ok=false;
    256         int pcount=count;
     247        char format = g.getFormat();
     248        GenoOperators *gf = getOper_f(format);
     249        if (gf == NULL)
     250                return Geno(SString::empty(), -1, SString::empty(), SString::sprintf("GENOPER_NOOPER: Mutate(): don't know how to handle genetic format %c", format));
     251        Geno gv = g;
     252        bool canvalidate = true;
     253        if (testValidity(gv, canvalidate) > 0 && canvalidate == false)
     254                return Geno("", -1, "", "GENOPER_OPFAIL: Mutate(): cannot validate invalid source genotype");
     255        bool ok = false;
     256        int pcount = count;
    257257        while (!ok)
    258258        {
    259                 char *gn=strdup(gv.getGene()); //copy for mutation
    260                 chg=0;
    261                 if (gf->mutate(gn,chg,method)==GENOPER_OK)
     259                char *gn = strdup(gv.getGene()); //copy for mutation
     260                chg = 0;
     261                if (gf->mutate(gn, chg, method) == GENOPER_OK)
    262262                {
    263263                        ErrorHandler eh(ErrorHandler::StoreFirstMessage); //mute testValidity()
    264                         Geno G(gn,gv.getFormat(),"","");
    265                         canvalidate=true;
    266                         int res=testValidity(G,canvalidate);
    267                         if (res==GENOPER_OK && canvalidate==false) {valid_m++; ok=true;} else
    268                                 if (res>0 && canvalidate==false) invalid_m++; else
    269                                 {validated_m++; ok=true;}
    270                                 if (ok) gv=G;
    271                 } else failed_m++;
     264                        Geno G(gn, gv.getFormat(), "", "");
     265                        canvalidate = true;
     266                        int res = testValidity(G, canvalidate);
     267                        if (res == GENOPER_OK && canvalidate == false) { valid_m++; ok = true; }
     268                        else
     269                                if (res > 0 && canvalidate == false) invalid_m++; else
     270                                {
     271                                        validated_m++; ok = true;
     272                                }
     273                        if (ok) gv = G;
     274                }
     275                else failed_m++;
    272276                free(gn);
    273277                count++;
    274                 if (!ok && (count-pcount>100))
    275                 {
    276                         FMprintf("GenMan","Mutate",2,"Tried 100x and failed: %s",(const char*)g.getGene());
    277                         return Geno("",-1,"","GENOPER_OPFAIL: Mutate() tried 100x and failed");
    278                 }
    279         }
    280         mutchg+=chg;
    281         if (history) saveLink((const char*)g.getGene(),(const char*)gv.getGene(),chg);
     278                if (!ok && (count - pcount > 100))
     279                {
     280                        FMprintf("GenMan", "Mutate", 2, "Tried 100x and failed: %s", (const char*)g.getGene());
     281                        return Geno("", -1, "", "GENOPER_OPFAIL: Mutate() tried 100x and failed");
     282                }
     283        }
     284        mutchg += chg;
     285        if (history) saveLink((const char*)g.getGene(), (const char*)gv.getGene(), chg);
    282286        SString mutinfo;
    283         if (extmutinfo == 0) mutinfo = SString::sprintf("%.2f%% mutation of '%s'",100*chg,(const char*)g.getName()); else
     287        if (extmutinfo == 0) mutinfo = SString::sprintf("%.2f%% mutation of '%s'", 100 * chg, (const char*)g.getName()); else
    284288                if (extmutinfo == 1) mutinfo = SString::sprintf("%.2f%% mutation(%d) of '%s'", 100 * chg, method, (const char*)g.getName()); else
    285289                        mutinfo = SString::sprintf("%.2f%% mutation(%s) of '%s'", 100 * chg, gf->mutation_method_names ? gf->mutation_method_names[method] : "unspecified method name", (const char*)g.getName());
     
    320324                {
    321325                        char *gn;
    322                         if (g1n[0] && g2n[0]) if (randomN(2) == 0) g1n[0] = 0; else g2n[0] = 0; //we want only one
     326                        if (g1n[0] && g2n[0]) if (randomN(2) == 0) g1n[0] = 0; else g2n[0] = 0; //both provided? we want only one
    323327                        if (g1n[0]) { gn = g1n; chg = chg1; }
    324328                        else { gn = g2n; chg = chg2; }
     
    474478        int ind = operformats.find(format);
    475479        if (ind == -1) return NULL;
    476         int ktoryopformatu = seloper[ind];
     480        int which_oper_of_format = seloper[ind];
    477481        for (unsigned int i = 0; i < oper_fx_list.size(); i++)
    478482                if (oper_fx_list[i]->supported_format == format)
    479                         if (ktoryopformatu == 0) return oper_fx_list[i]; else ktoryopformatu--;
     483                        if (which_oper_of_format == 0) return oper_fx_list[i]; else which_oper_of_format--;
    480484        return NULL; //should never happen
    481485}
  • cpp/frams/genetics/oper_fx.cpp

    r158 r168  
    99#include <frams/util/rndutil.h>
    1010
    11 static double distrib_force[]=   // for '!'
    12 {
    13 3,                 // distribution 0 -__/ +1
    14 0.001, 0.2,        // "slow" neurons
    15 0.001, 1,
    16     1, 1,          // "fast" neurons
     11static double distrib_force[] =   // for '!'
     12{
     13        3,             // distribution 0 -__/ +1
     14        0.001, 0.2,    // "slow" neurons
     15        0.001, 1,
     16        1, 1,          // "fast" neurons
    1717};
    18 static double distrib_inertia[]=  // for '='
    19 {
    20 2,                 // distribution 0 |..- +1
    21   0, 0,            // "fast" neurons
    22 0.7, 0.98,
     18static double distrib_inertia[] =  // for '='
     19{
     20        2,             // distribution 0 |..- +1
     21        0, 0,          // "fast" neurons
     22        0.7, 0.98,
    2323};
    24 static double distrib_sigmo[]=  // for '/'
    25 {
    26 5,                 // distribution -999 -..-^-..- +999
    27 -999, -999,        //"perceptron"
    28  999, 999,
    29   -5, -1,          // nonlinear
    30    1, 5,
    31   -1, 1,           // ~linear
     24static double distrib_sigmo[] =  // for '/'
     25{
     26        5,             // distribution -999 -..-^-..- +999
     27        -999, -999,    //"perceptron"
     28        999, 999,
     29        -5, -1,        // nonlinear
     30        1, 5,
     31        -1, 1,         // ~linear
    3232};
    3333
    3434
    35 int GenoOperators::roulette(const double *probtab,const int count)
    36 {
    37    double sum=0;
    38    int i;
    39    for (i=0;i<count;i++) sum+=probtab[i];
    40    double sel=rnd01*sum;
    41    for (sum=0,i=0;i<count;i++) {sum+=probtab[i]; if (sel<sum) return i;}
    42    return -1;
    43 }
    44 
    45 bool GenoOperators::getMinMaxDef(ParamInterface *p,int i,double &mn,double &mx,double &def)
    46 {
    47    mn=mx=def=0;
    48    int defined=0;
    49    if (p->type(i)[0]=='f')
    50    {
    51       double _mn=0,_mx=1,_def=0.5;
    52       defined=p->getMinMax(i,_mn,_mx,_def);
    53       if (defined==1) _mx=_mn+1.0;
    54       if (_mx<_mn && defined==3) _mn=_mx=_def; //only default was defined, let's assume min=max=default
    55       if (defined<3) _def=(_mn+_mx)/2.0;
    56       mn=_mn; mx=_mx; def=_def;
    57    }
    58    if (p->type(i)[0]=='d')
    59    {
    60       long _mn=0,_mx=1,_def=0;
    61       defined=p->getMinMax(i,_mn,_mx,_def);
    62       if (defined==1) _mx=_mn+1;
    63       if (_mx<_mn && defined==3) _mn=_mx=_def; //only default was defined, let's assume min=max=default
    64       if (defined<3) _def=(_mn+_mx)/2;
    65       mn=_mn; mx=_mx; def=_def;
    66    }
    67    return defined==3;
     35int GenoOperators::roulette(const double *probtab, const int count)
     36{
     37        double sum = 0;
     38        int i;
     39        for (i = 0; i < count; i++) sum += probtab[i];
     40        double sel = rnd01*sum;
     41        for (sum = 0, i = 0; i < count; i++) { sum += probtab[i]; if (sel < sum) return i; }
     42        return -1;
     43}
     44
     45bool GenoOperators::getMinMaxDef(ParamInterface *p, int i, double &mn, double &mx, double &def)
     46{
     47        mn = mx = def = 0;
     48        int defined = 0;
     49        if (p->type(i)[0] == 'f')
     50        {
     51                double _mn = 0, _mx = 1, _def = 0.5;
     52                defined = p->getMinMax(i, _mn, _mx, _def);
     53                if (defined == 1) _mx = _mn + 1.0;
     54                if (_mx < _mn && defined == 3) _mn = _mx = _def; //only default was defined, let's assume min=max=default
     55                if (defined < 3) _def = (_mn + _mx) / 2.0;
     56                mn = _mn; mx = _mx; def = _def;
     57        }
     58        if (p->type(i)[0] == 'd')
     59        {
     60                long _mn = 0, _mx = 1, _def = 0;
     61                defined = p->getMinMax(i, _mn, _mx, _def);
     62                if (defined == 1) _mx = _mn + 1;
     63                if (_mx < _mn && defined == 3) _mn = _mx = _def; //only default was defined, let's assume min=max=default
     64                if (defined < 3) _def = (_mn + _mx) / 2;
     65                mn = _mn; mx = _mx; def = _def;
     66        }
     67        return defined == 3;
    6868}
    6969
    7070int GenoOperators::selectRandomProperty(Neuro* n)
    7171{
    72    int neuext=n->extraProperties().getPropCount(),
    73        neucls=n->getClass()==NULL?0:n->getClass()->getProperties().getPropCount();
    74    if (neuext+neucls==0) return -1; //no properties in this neuron
    75    int index=randomN(neuext+neucls);
    76    if (index>=neuext) index=index-neuext+100;
    77    return index;
    78 }
    79 
    80 double GenoOperators::mutateNeuProperty(double current,Neuro *n,int i)
    81 {
    82    if (i==-1) return mutateCreepNoLimit('f',current,-10,10); //i==-1: mutating weight of neural connection
    83    Param p;
    84    if (i>=100) {i-=100; p=n->getClass()->getProperties();}
    85       else p=n->extraProperties();
    86    double newval=current;
    87    /*bool ok=*/getMutatedProperty(p,i,current,newval);
    88    return newval;
    89 }
    90 
    91 bool GenoOperators::mutatePropertyNaive(ParamInterface &p,int i)
    92 {
    93    double mn,mx,df;
    94    if (p.type(i)[0]!='f' && p.type(i)[0]!='d') return false; //don't know how to mutate
    95    getMinMaxDef(&p,i,mn,mx,df);
    96 
    97    ExtValue ev;
    98    p.get(i,ev);
    99    ev.setDouble(mutateCreep(p.type(i)[0],ev.getDouble(),mn,mx));
    100    p.set(i,ev);
    101    return true;
    102 }
    103 
    104 bool GenoOperators::mutateProperty(ParamInterface &p,int i)
    105 {
    106    double newval;
    107    ExtValue ev;
    108    p.get(i,ev);
    109    bool ok=getMutatedProperty(p,i,ev.getDouble(),newval);
    110    if (ok) {ev.setDouble(newval); p.set(i,ev);}
    111    return ok;
    112 }
    113 
    114 bool GenoOperators::getMutatedProperty(ParamInterface &p,int i,double oldval,double &newval)
    115 {
    116    newval=0;
    117    if (p.type(i)[0]!='f' && p.type(i)[0]!='d') return false; //don't know how to mutate
    118    const char *n=p.id(i),*na=p.name(i);
    119      if (strcmp(n,"si")==0 && strcmp(na,"Sigmoid")==0) newval=CustomRnd(distrib_sigmo); else
    120      if (strcmp(n,"in")==0 && strcmp(na,"Inertia")==0) newval=CustomRnd(distrib_inertia); else
    121      if (strcmp(n,"fo")==0 && strcmp(na,"Force")==0) newval=CustomRnd(distrib_force); else
    122      {
    123        double mn,mx,df;
    124        getMinMaxDef(&p,i,mn,mx,df);
    125        newval=mutateCreep(p.type(i)[0],oldval,mn,mx);
    126      }
    127    return true;
    128 }
    129 
    130 double GenoOperators::mutateCreepNoLimit(char type,double current,double mn,double mx)
    131 {
    132    double result=RndGen.Gauss(current,(mx-mn)/2/5); // /halfinterval, 5 times narrower
    133    if (type=='d') {result=int(result+0.5); if (result==current) result+=randomN(2)*2-1;}
    134     else result=floor(result*1000+0.5)/1000.0; //round
    135    return result;
     72        int neuext = n->extraProperties().getPropCount(),
     73                neucls = n->getClass() == NULL ? 0 : n->getClass()->getProperties().getPropCount();
     74        if (neuext + neucls == 0) return -1; //no properties in this neuron
     75        int index = randomN(neuext + neucls);
     76        if (index >= neuext) index = index - neuext + 100;
     77        return index;
     78}
     79
     80double GenoOperators::mutateNeuProperty(double current, Neuro *n, int i)
     81{
     82        if (i == -1) return mutateCreepNoLimit('f', current, -10, 10); //i==-1: mutating weight of neural connection
     83        Param p;
     84        if (i >= 100) { i -= 100; p = n->getClass()->getProperties(); }
     85        else p = n->extraProperties();
     86        double newval = current;
     87        /*bool ok=*/getMutatedProperty(p, i, current, newval);
     88        return newval;
     89}
     90
     91bool GenoOperators::mutatePropertyNaive(ParamInterface &p, int i)
     92{
     93        double mn, mx, df;
     94        if (p.type(i)[0] != 'f' && p.type(i)[0] != 'd') return false; //don't know how to mutate
     95        getMinMaxDef(&p, i, mn, mx, df);
     96
     97        ExtValue ev;
     98        p.get(i, ev);
     99        ev.setDouble(mutateCreep(p.type(i)[0], ev.getDouble(), mn, mx));
     100        p.set(i, ev);
     101        return true;
     102}
     103
     104bool GenoOperators::mutateProperty(ParamInterface &p, int i)
     105{
     106        double newval;
     107        ExtValue ev;
     108        p.get(i, ev);
     109        bool ok = getMutatedProperty(p, i, ev.getDouble(), newval);
     110        if (ok) { ev.setDouble(newval); p.set(i, ev); }
     111        return ok;
     112}
     113
     114bool GenoOperators::getMutatedProperty(ParamInterface &p, int i, double oldval, double &newval)
     115{
     116        newval = 0;
     117        if (p.type(i)[0] != 'f' && p.type(i)[0] != 'd') return false; //don't know how to mutate
     118        const char *n = p.id(i), *na = p.name(i);
     119        if (strcmp(n, "si") == 0 && strcmp(na, "Sigmoid") == 0) newval = CustomRnd(distrib_sigmo); else
     120                if (strcmp(n, "in") == 0 && strcmp(na, "Inertia") == 0) newval = CustomRnd(distrib_inertia); else
     121                        if (strcmp(n, "fo") == 0 && strcmp(na, "Force") == 0) newval = CustomRnd(distrib_force); else
     122                        {
     123                                double mn, mx, df;
     124                                getMinMaxDef(&p, i, mn, mx, df);
     125                                newval = mutateCreep(p.type(i)[0], oldval, mn, mx);
     126                        }
     127        return true;
     128}
     129
     130double GenoOperators::mutateCreepNoLimit(char type, double current, double mn, double mx)
     131{
     132        double result = RndGen.Gauss(current, (mx - mn) / 2 / 5); // /halfinterval, 5 times narrower
     133        if (type == 'd') { result = int(result + 0.5); if (result == current) result += randomN(2) * 2 - 1; }
     134        else result = floor(result * 1000 + 0.5) / 1000.0; //round
     135        return result;
    136136}
    137137
     
    180180{
    181181        SListTempl<NeuroClass*> active;
    182    for(int i=0;i<Neuro::getClassCount();i++)
    183       if (Neuro::getClass(i)->genactive) active+=Neuro::getClass(i);
    184    if (!active==0) return NULL; else return active(randomN(!active));
     182        for (int i = 0; i < Neuro::getClassCount(); i++)
     183                if (Neuro::getClass(i)->genactive) active += Neuro::getClass(i);
     184        if (!active == 0) return NULL; else return active(randomN(!active));
    185185}
    186186
    187187NeuroClass* GenoOperators::parseNeuroClass(char*& s)
    188188{
    189    int len=strlen(s);
    190    int Len=0;
    191    NeuroClass *I=NULL;
    192    for(int i=0;i<Neuro::getClassCount();i++)
    193    {
    194       const char *n=Neuro::getClass(i)->name;
    195       int l=strlen(n);
    196       if (len>=l && l>Len && (strncmp(s,n,l)==0)) {I=Neuro::getClass(i); Len=l;}
    197    }
    198    s+=Len;
    199    return I;
    200 }
    201 
    202 Neuro* GenoOperators::findNeuro(const Model *m,const NeuroClass *nc)
    203 {
    204   if (!m) return NULL;
    205   for(int i=0;i<m->getNeuroCount();i++)
    206      if (m->getNeuro(i)->getClass()==nc) return m->getNeuro(i);
    207   return NULL; //neuron of class 'nc' was not found
    208 }
    209 
    210 int GenoOperators::neuroClassProp(char*& s,NeuroClass *nc,bool also_v1_N_props)
    211 {
    212    int len=strlen(s);
    213    int Len=0,I=-1;
    214    if (nc)
    215    {
    216       Param p=nc->getProperties();
    217       for(int i=0;i<p.getPropCount();i++)
    218       {
    219          const char *n=p.id(i);
    220          int l=strlen(n);
    221          if (len>=l && l>Len && (strncmp(s,n,l)==0)) {I=100+i; Len=l;}
    222          if (also_v1_N_props) //recognize old properties symbols /=!
    223          {
    224             if (strcmp(n,"si")==0) n="/"; else
    225             if (strcmp(n,"in")==0) n="="; else
    226             if (strcmp(n,"fo")==0) n="!";
    227             l=strlen(n);
    228             if (len>=l && l>Len && (strncmp(s,n,l)==0)) {I=100+i; Len=l;}
    229          }
    230       }
    231    }
    232    Neuro n;
    233    Param p=n.extraProperties();
    234    for(int i=0;i<p.getPropCount();i++)
    235    {
    236       const char *n=p.id(i);
    237       int l=strlen(n);
    238       if (len>=l && l>Len && (strncmp(s,n,l)==0)) {I=i; Len=l;}
    239    }
    240    s+=Len;
    241    return I;
     189        int len = strlen(s);
     190        int Len = 0;
     191        NeuroClass *I = NULL;
     192        for (int i = 0; i<Neuro::getClassCount(); i++)
     193        {
     194                const char *n = Neuro::getClass(i)->name;
     195                int l = strlen(n);
     196                if (len >= l && l>Len && (strncmp(s, n, l) == 0)) { I = Neuro::getClass(i); Len = l; }
     197        }
     198        s += Len;
     199        return I;
     200}
     201
     202Neuro* GenoOperators::findNeuro(const Model *m, const NeuroClass *nc)
     203{
     204        if (!m) return NULL;
     205        for (int i = 0; i < m->getNeuroCount(); i++)
     206                if (m->getNeuro(i)->getClass() == nc) return m->getNeuro(i);
     207        return NULL; //neuron of class 'nc' was not found
     208}
     209
     210int GenoOperators::neuroClassProp(char*& s, NeuroClass *nc, bool also_v1_N_props)
     211{
     212        int len = strlen(s);
     213        int Len = 0, I = -1;
     214        if (nc)
     215        {
     216                Param p = nc->getProperties();
     217                for (int i = 0; i<p.getPropCount(); i++)
     218                {
     219                        const char *n = p.id(i);
     220                        int l = strlen(n);
     221                        if (len >= l && l>Len && (strncmp(s, n, l) == 0)) { I = 100 + i; Len = l; }
     222                        if (also_v1_N_props) //recognize old properties symbols /=!
     223                        {
     224                                if (strcmp(n, "si") == 0) n = "/"; else
     225                                        if (strcmp(n, "in") == 0) n = "="; else
     226                                                if (strcmp(n, "fo") == 0) n = "!";
     227                                l = strlen(n);
     228                                if (len >= l && l > Len && (strncmp(s, n, l) == 0)) { I = 100 + i; Len = l; }
     229                        }
     230                }
     231        }
     232        Neuro n;
     233        Param p = n.extraProperties();
     234        for (int i = 0; i<p.getPropCount(); i++)
     235        {
     236                const char *n = p.id(i);
     237                int l = strlen(n);
     238                if (len >= l && l>Len && (strncmp(s, n, l) == 0)) { I = i; Len = l; }
     239        }
     240        s += Len;
     241        return I;
    242242}
    243243
    244244bool GenoOperators::isWS(const char c)
    245 {return c==' ' || c=='\n' || c=='\t' || c=='\r';}
     245{
     246        return c == ' ' || c == '\n' || c == '\t' || c == '\r';
     247}
    246248
    247249void GenoOperators::skipWS(char *&s)
    248250{
    249         if (s==NULL)
     251        if (s == NULL)
    250252                FramMessage("GenoOperators", "skipWS", "NULL reference!", FMLV_WARN);
    251253        else
     
    253255}
    254256
    255 bool GenoOperators::areAlike(char *g1,char *g2)
     257bool GenoOperators::areAlike(char *g1, char *g2)
    256258{
    257259        while (*g1 || *g2)
     
    260262                skipWS(g2);
    261263                if (*g1 != *g2) return false; //when difference
    262       if (!*g1 && !*g2) break; //both end
    263       g1++;
    264       g2++;
     264                if (!*g1 && !*g2) break; //both end
     265                g1++;
     266                g2++;
    265267        }
    266268        return true; //equal
    267269}
    268270
    269 char* GenoOperators::strchrn0(const char *str,char ch)
    270 { return ch==0?NULL:strchr((char*)str,ch); }
     271char* GenoOperators::strchrn0(const char *str, char ch)
     272{
     273        return ch == 0 ? NULL : strchr((char*)str, ch);
     274}
    271275
    272276bool GenoOperators::isNeuroClassName(const char firstchar)
    273277{
    274    return isupper(firstchar) || firstchar=='|' || firstchar=='@' || firstchar=='*';
    275 }
    276 
     278        return isupper(firstchar) || firstchar == '|' || firstchar == '@' || firstchar == '*';
     279}
     280
Note: See TracChangeset for help on using the changeset viewer.