Helper function that creates a set of three objects used for basic
  experiments.

  :return:   (list(list(tuple))  List of lists of feature / location pairs.
171436
def createThreeObjects():
  
  objectA = zip(range(10), range(10))
  objectB = [(0, 0), (2, 2), (1, 1), (1, 4), (4, 2), (4, 1)]
  objectC = [(0, 0), (1, 1), (3, 1), (0, 1)]
  return [objectA, objectB, objectC]
749431
def feature_list():
    
    lib_features_c_array = ctypes.POINTER(Feature)()
    lib_features_size = ctypes.c_size_t()
    check_call(_LIB.MXLibInfoFeatures(ctypes.byref(lib_features_c_array), ctypes.byref(lib_features_size)))
    features = [lib_features_c_array[i] for i in range(lib_features_size.value)]
    return features
318815
def fromTuple(self, locationTuple):
        
        for key, value in locationTuple:
            try:
                self[key] = float(value)
            except TypeError:
                self[key] = tuple([float(v) for v in value])
994719
def _construct_from_dataframe(self):
        
        direct_edges = {}
        feature_side_grouping = self.feature_pathway_df.groupby(
            ["feature", "side"])
        for (feature, _), group in feature_side_grouping:
            co_occurring_pathways = group["pathway"].tolist()
            pairings = list(itertools.combinations(co_occurring_pathways, 2))
            if not pairings:
                continue
            self.features.add(feature)
            for pathway0, pathway1 in pairings:
                vertex0_id = self.add_pathway(pathway0)
                vertex1_id = self.add_pathway(pathway1)
                new_edge = self.edge_tuple(vertex0_id, vertex1_id)
                if new_edge not in direct_edges:
                    direct_edges[new_edge] = []
                direct_edges[new_edge].append(feature)
        self._augment_network(direct_edges)
703532
def _make_list(predictions, targets):
  """"""
  #  Our models sometimes return predictions in lists, make it a list always.
  # TODO(lukaszkaiser): make abstractions for nested structures and refactor.
  if not isinstance(predictions, (list, tuple)):
    if isinstance(targets, (list, tuple)):
      raise ValueError("Targets are a list or tuple but predictions are not.")
    predictions, targets = [predictions], [targets]
  if len(predictions) != len(targets):
    raise ValueError("Predictions and targets have different lengths.")
  return list(predictions), list(targets)
1180520
def build_shapes(self):
        
        self.all_shapes = []  # @todo: keep adding?

        qres = self.sparqlHelper.getShapes()

        for candidate in qres:

            test_existing_cl = self.get_any_entity(uri=candidate[0])
            if not test_existing_cl:
                # create it
                self.all_shapes += [OntoShape(candidate[0], None, self.namespaces)]
            else:
                pass

        # add more data
        shacl = rdflib.Namespace('http://www.w3.org/ns/shacl#')

        for aShape in self.all_shapes:

            aShape.rdftype = shacl['Shape']
            aShape.triples = self.sparqlHelper.entityTriples(aShape.uri)
            aShape._buildGraph()  # force construction of mini graph

            aShape.sparqlHelper = self.sparqlHelper

            # attach to a class
            for uri in aShape.getValuesForProperty(shacl['targetClass']):
                aclass = self.get_class(str(uri))
                if aclass:
                    aShape.targetClasses += [aclass]
                    aclass.all_shapes += [aShape]
                    for propertyUri in aShape.getValuesForProperty(shacl['path']): #add shaped properties of this class. later can be used for ontodocs
                        propType = self.get_property(str(propertyUri))
                        if propType:
                            aclass.shapedProperties += [{'shape': aShape, 'property': propType}]



        # sort alphabetically
        self.all_shapes = sorted(self.all_shapes, key=lambda x: x.qname)

        # compute top layer
        exit = []
        for c in self.all_shapes:
            if not c.parents():
                exit += [c]
        self.toplayer_shapes = exit
201699
def points(self):
        
        feature = geojson.Feature(geometry=self._geom)
        points_coords = list(geojson.utils.coords(feature))
        return [Point(p[0], p[1]) for p in points_coords]
749446
def inferObjectsWithRandomMovements(self):
    
    for objectName, objectFeatures in self.objects.iteritems():
      self.reset()

      inferred = False
      prevTouchSequence = None

      for _ in xrange(4):

        while True:
          touchSequence = list(objectFeatures)
          random.shuffle(touchSequence)

          if prevTouchSequence is not None:
            if touchSequence[0] == prevTouchSequence[-1]:
              continue

          break

        for i, feature in enumerate(touchSequence):
          locationOnObject = (feature["top"] + feature["height"]/2,
                              feature["left"] + feature["width"]/2)
          self.move(objectName, locationOnObject)

          featureName = feature["name"]
          featureSDR = self.features[featureName]
          self.sense(featureSDR, learn=False)

          inferred = (
            set(self.objectLayer.getActiveCells()) ==
            set(self.objectRepresentations[objectName]) and

            set(self.inputLayer.getActiveCells()) ==
            set(self.inputRepresentations[(objectName,
                                           locationOnObject,
                                           featureName)]) and

            set(self.getActiveLocationCells()) ==
            set(self.locationRepresentations[(objectName, locationOnObject)]))

          if inferred:
            break

        prevTouchSequence = touchSequence

        if inferred:
          break
1298214
def combine(self):
        
        self.pair, setup = self.combining_setup()
        self.cube(setup)
        actual = self.combining_search()
        self.cube(actual)
        return setup + actual
502922
def gaussian_multi_polygons(points, n=10):
    
    polygons = gaussian_polygons(points, n*2)
    # Randomly stitch them together.
    polygon_pairs = [shapely.geometry.MultiPolygon(list(pair)) for pair in np.array_split(polygons.values, n)]
    return gpd.GeoSeries(polygon_pairs)
380263
def sampleLocationFromFeature(self, feature):
    
    if feature == "surface":
      return self.sampleLocationFromFeature('face') # Temporary workaround for surfaces
    elif feature=="face":
      indx = self.rng.choice(range(self.faces.count))
      rndFace = self.faces[indx]
      return self._sampleLocationOnFace(rndFace)

    elif feature == "edge":
      indx = self.rng.choice(range(self.faces.count))
      rndFace = self.faces[indx]
      rndVertices = self.rng.sample(self.vertices[rndFace],2)
      return self._sampleLocationOnEdge(rndVertices)

    elif feature == "vertex":
      rndVertexIndx = self.rng.choice(range(self.vertices.count))
      return np.array(self.vertices[rndVertexIndx].tolist())

    elif feature == "surface":
      return self.sampleLocationFromFeature("face")      # Temporary workaround for surfaces
    elif feature == "random":
      return self.sampleLocation()
    else:
      raise NameError("No such feature in {}: {}".format(self, feature))
550970
def load_features(paths: List[str],
                  expected_shape: Optional[tuple] = None) -> List[np.ndarray]:
    
    data = []  # type: List[np.ndarray]
    for path in paths:
        data.append(load_feature(path, expected_shape))
    return data
336951
def _create_placeholders(self, n_features):
        
        self.input_data = tf.placeholder(tf.float32, [None, n_features],
                                         name='x-input')
        self.hrand = tf.placeholder(tf.float32, [None, self.num_hidden],
                                    name='hrand')
        self.vrand = tf.placeholder(tf.float32, [None, n_features],
                                    name='vrand')
        # not used in this model, created just to comply with
        # unsupervised_model.py
        self.input_labels = tf.placeholder(tf.float32)
        self.keep_prob = tf.placeholder(tf.float32, name='keep-probs')
824664
def get_3_3_tuple_list(self,obj,default=None):
        
        if is_sequence3(obj):
            return [self.get_3_3_tuple(o,default) for o in obj]
        return [self.get_3_3_tuple(obj,default)]
1114261
def features(self):
        
        if 'Features' in self._signature.subpackets:
            return next(iter(self._signature.subpackets['Features'])).flags
        return set()
1366058
def get_subgraph_for_concept_pairs(
        self, concepts: List[str], cutoff: Optional[int] = None
    ):
        
        path_generator = (
            nx.all_simple_paths(self, source, target, cutoff=cutoff)
            for source, target in permutations(concepts, 2)
        )
        paths = chain.from_iterable(path_generator)
        return AnalysisGraph(self.subgraph(set(chain.from_iterable(paths))))
852817
def addObject(self, featureIndices, name=None):
    
    if name is None:
      name = len(self.objects)

    sequence = []
    for f in featureIndices: sequence += [(0, f,)]

    self.objects[name] = sequence