desugar layer_defs for adding activation, dropout layers etc
350921
function() {
        var new_defs = [];
        for(var i=0;i<defs.length;i++) {
          var def = defs[i];
          
          if(def.type==='softmax' || def.type==='svm') {
            // add an fc layer here, there is no reason the user should
            // have to worry about this and we almost always want to
            new_defs.push({type:'fc', num_neurons: def.num_classes});
          }

          if(def.type==='regression') {
            // add an fc layer here, there is no reason the user should
            // have to worry about this and we almost always want to
            new_defs.push({type:'fc', num_neurons: def.num_neurons});
          }

          if((def.type==='fc' || def.type==='conv') 
              && typeof(def.bias_pref) === 'undefined'){
            def.bias_pref = 0.0;
            if(typeof def.activation !== 'undefined' && def.activation === 'relu') {
              def.bias_pref = 0.1; // relus like a bit of positive bias to get gradients early
              // otherwise it's technically possible that a relu unit will never turn on (by chance)
              // and will never get any gradient and never contribute any computation. Dead relu.
            }
          }

          new_defs.push(def);

          if(typeof def.activation !== 'undefined') {
            if(def.activation==='relu') { new_defs.push({type:'relu'}); }
            else if (def.activation==='sigmoid') { new_defs.push({type:'sigmoid'}); }
            else if (def.activation==='tanh') { new_defs.push({type:'tanh'}); }
            else if (def.activation==='maxout') {
              // create maxout activation, and pass along group size, if provided
              var gs = def.group_size !== 'undefined' ? def.group_size : 2;
              new_defs.push({type:'maxout', group_size:gs});
            }
            else { console.log('ERROR unsupported activation ' + def.activation); }
          }
          if(typeof def.drop_prob !== 'undefined' && def.type !== 'dropout') {
            new_defs.push({type:'dropout', drop_prob: def.drop_prob});
          }

        }
        return new_defs;
      }
212708
def addfunctions2new(abunch, key):
    """"""
    snames = [
        "BuildingSurface:Detailed",
        "Wall:Detailed",
        "RoofCeiling:Detailed",
        "Floor:Detailed",
        "FenestrationSurface:Detailed",
        "Shading:Site:Detailed",
        "Shading:Building:Detailed",
        "Shading:Zone:Detailed", ]
    snames = [sname.upper() for sname in snames]
    if key in snames:
        func_dict = {
            'area': fh.area,
            'height': fh.height,  # not working correctly
            'width': fh.width,  # not working correctly
            'azimuth': fh.azimuth,
            'tilt': fh.tilt,
            'coords': fh.getcoords,  # needed for debugging
        }
        try:
            abunch.__functions.update(func_dict)
        except KeyError as e:
            abunch.__functions = func_dict
    return abunch
806015
def layered(self, images, only_pushable=False):
        """"""
        if only_pushable:
            operate_on = dict((image, instance) for image, instance in images.items() if instance.image_index)
        else:
            operate_on = images

        layers = Layers(operate_on, all_images=images)
        layers.add_all_to_layers()
        for layer in layers.layered:
            buf = []
            for image_name, image in layer:
                if image.image_index:
                    buf.append((image_name, image))
            if buf:
                yield buf
1260187
def create(fc_layers=None, dropout=None, pretrained=True):
    
    def instantiate(**_):
        return Resnet34(fc_layers, dropout, pretrained)

    return ModelFactory.generic(instantiate)
1358311
def addLayers(self, *arg, **kw):
        
        netType = "serial"
        if "type" in kw:
            netType = kw["type"]
        self.addLayer('input', arg[0])
        hiddens = []
        contexts = []
        if len(arg) > 3: # FIXME: add context for each
            hcount = 0
            for hidc in arg[1:-1]:
                name = 'hidden%d' % hcount
                cname = 'context%d' % hcount
                self.addLayer(name, hidc)
                hiddens.append(name)
                self.addContextLayer(cname, hidc, name)
                hiddens.append((cname, name))
                hcount += 1
        elif len(arg) == 3:
                name = 'hidden'
                self.addContextLayer('context', arg[1], name)
                self.addLayer(name, arg[1])
                hiddens.append(name)
                contexts.append(('context', name))
        elif len(arg) == 2:
            pass
        else:
            raise AttributeError("not enough layers! need >= 2")
        self.addLayer('output', arg[-1])
        # Connect contexts
        for (fromName, toName) in contexts:
            self.connect(fromName, toName)
        lastName = "input"
        for name in hiddens:
            if netType == "parallel":
                self.connect('input', name)
                self.connect(name, 'output')
            else: # serial
                self.connect(lastName, name)
                lastName = name
        if netType == "serial" or lastName == "input":
            self.connect(lastName, "output")
182662
def togglekml(self, layername):
        ''''''
        #Strip quotation marks if neccessary
        if layername.startswith('"') and layername.endswith('"'):
            layername = layername[1:-1]
        #toggle layer off (plus associated text element)
        if layername in self.curlayers:
            for layer in self.curlayers:
                if layer == layername:
                    self.mpstate.map.remove_object(layer)
                    self.curlayers.remove(layername)
                    if layername in self.curtextlayers:
                        for clayer in self.curtextlayers:
                            if clayer == layername:
                                self.mpstate.map.remove_object(clayer)
                                self.curtextlayers.remove(clayer)
        #toggle layer on (plus associated text element)
        else:
            for layer in self.allayers:
                if layer.key == layername:
                    self.mpstate.map.add_object(layer)
                    self.curlayers.append(layername)
                    for alayer in self.alltextlayers:
                        if alayer.key == layername:
                            self.mpstate.map.add_object(alayer)
                            self.curtextlayers.append(layername)
        self.menu_needs_refreshing = True
429072
def keras_dropout(layer, rate):
    '''
    '''

    from keras import layers

    input_dim = len(layer.input.shape)
    if input_dim == 2:
        return layers.SpatialDropout1D(rate)
    elif input_dim == 3:
        return layers.SpatialDropout2D(rate)
    elif input_dim == 4:
        return layers.SpatialDropout3D(rate)
    else:
        return layers.Dropout(rate)
288398
function reload() {
  eval($("#layerdef").val());

  // refresh buttons
  var t = '';
  for(var i=1;i<net.layers.length-1;i++) { // ignore input and regression layers (first and last)
    var butid = "button" + i;
    t += "<input id=\""+butid+"\" value=\"" + net.layers[i].layer_type +"\" type=\"submit\" onclick=\"updateLix("+i+")\" style=\"width:80px; height: 30px; margin:5px;\";>";
  }
  $("#layer_ixes").html(t);
  $("#button"+lix).css('background-color', '#FFA');
}
338794
function addDebugLayers (node, tree) {
    for (let layer in node) {
        let counts = node[layer];
        addLayerDebugEntry(tree, layer, counts.features, counts.geoms, counts.styles, counts.base);
        if (counts.layers) {
            tree[layer].layers = tree[layer].layers || {};
            addDebugLayers(counts.layers, tree[layer].layers); // process child layers
        }
    }
}
319216
def addfunctions(dtls, bunchdt):
    """"""
    snames = [
        "BuildingSurface:Detailed",
        "Wall:Detailed",
        "RoofCeiling:Detailed",
        "Floor:Detailed",
        "FenestrationSurface:Detailed",
        "Shading:Site:Detailed",
        "Shading:Building:Detailed",
        "Shading:Zone:Detailed", ]
    for sname in snames:
        if sname.upper() in bunchdt:
            surfaces = bunchdt[sname.upper()]
            for surface in surfaces:
                func_dict = {
                    'area': fh.area,
                    'height': fh.height,  # not working correctly
                    'width': fh.width,  # not working correctly
                    'azimuth': fh.azimuth,
                    'tilt': fh.tilt,
                    'coords': fh.getcoords,  # needed for debugging
                }
                try:
                    surface.__functions.update(func_dict)
                except KeyError as e:
                    surface.__functions = func_dict
734041
function debugOrdering(g) {
  var layerMatrix = util.buildLayerMatrix(g);

  var h = new Graph({ compound: true, multigraph: true }).setGraph({});

  _.forEach(g.nodes(), function(v) {
    h.setNode(v, { label: v });
    h.setParent(v, "layer" + g.node(v).rank);
  });

  _.forEach(g.edges(), function(e) {
    h.setEdge(e.v, e.w, {}, e.name);
  });

  _.forEach(layerMatrix, function(layer, i) {
    var layerV = "layer" + i;
    h.setNode(layerV, { rank: "same" });
    _.reduce(layer, function(u, v) {
      h.setEdge(u, v, { style: "invis" });
      return v;
    });
  });

  return h;
}
329724
def _insert_layer_after(self, layer_idx, new_layer, new_keras_layer):
        
        # reminder: new_keras_layer is not part of the original Keras network,
        # so it's input / output blob information is missing. It serves only as
        # a parameter holder.
        layer = self.layer_list[layer_idx]
        self.layer_list.insert(layer_idx+1, new_layer)
        self.keras_layer_map[new_layer] = new_keras_layer
        successors = self.get_successors(layer)
        # add edge layer -> new_layer
        self._add_edge(layer, new_layer)
        # add edges new_layer -> layer_successor, remove layer -> successor
        for succ in successors:
            self._add_edge(new_layer, succ)
            self._remove_edge(layer, succ)
270845
def monkey_patch_keywords(layer):
    
    keyword_io = KeywordIO()
    try:
        layer.keywords = keyword_io.read_keywords(layer)
    except (NoKeywordsFoundError, MetadataReadError):
        layer.keywords = {}

    if not layer.keywords.get('inasafe_fields'):
        layer.keywords['inasafe_fields'] = {}
    if not layer.keywords.get('layer_purpose'):
        layer.keywords['layer_purpose'] = 'undefined'
70533
def _build_layers(self, inputs, num_outputs, options):
        

        hiddens = options.get("fcnet_hiddens")
        activation = get_activation_fn(options.get("fcnet_activation"))

        with tf.name_scope("fc_net"):
            i = 1
            last_layer = inputs
            for size in hiddens:
                label = "fc{}".format(i)
                last_layer = slim.fully_connected(
                    last_layer,
                    size,
                    weights_initializer=normc_initializer(1.0),
                    activation_fn=activation,
                    scope=label)
                i += 1
            label = "fc_out"
            output = slim.fully_connected(
                last_layer,
                num_outputs,
                weights_initializer=normc_initializer(0.01),
                activation_fn=None,
                scope=label)
            return output, last_layer
932630
def get_aligned_activations(layer):
    """"""
    activation_paths = [
        PATH_TEMPLATE.format(
            sanitize(layer.model_class.name), sanitize(layer.name), page
        )
        for page in range(NUMBER_OF_PAGES)
    ]
    activations = np.vstack([load(path) for path in activation_paths])
    assert np.all(np.isfinite(activations))
    return activations
620671
def _get_layer_converter_fn(layer):
    
    layer_type = type(layer)
    if layer_type in _KERAS_LAYER_REGISTRY:
        return _KERAS_LAYER_REGISTRY[layer_type]
    else:
        raise TypeError("Keras layer of type %s is not supported." % type(layer))
1048352
def add_buttons(self, classification):
        
        # Note(IS): Until we have good behaviour, we will disable cancel
        # button.
        # Add 3 buttons: Restore default, Cancel, Save

        # Restore default button, only for continuous layer (with threshold)
        if self.layer_mode == layer_mode_continuous['key']:
            self.restore_default_button = QPushButton(tr('Restore Default'))
            self.restore_default_button.clicked.connect(partial(
                self.restore_default_button_clicked,
                classification=classification))

        # Cancel button
        # cancel_button = QPushButton(tr('Cancel'))
        # cancel_button.clicked.connect(self.cancel_button_clicked)

        # Save button
        self.save_button = QPushButton(tr('Save'))
        self.save_button.clicked.connect(
            partial(self.save_button_clicked, classification=classification))

        button_layout = QHBoxLayout()
        button_layout.addStretch(1)
        button_layout.addWidget(self.restore_default_button)
        button_layout.addWidget(self.save_button)

        button_layout.setStretch(0, 3)
        button_layout.setStretch(1, 1)
        button_layout.setStretch(2, 1)
        # button_layout.setStretch(3, 1)

        self.right_layout.addLayout(button_layout)