<commit_before>/*
 * Copyright 2015 University of Basel, Graphics and Vision Research Group
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package scalismo.statisticalmodel.asm

import breeze.linalg.DenseVector
import scalismo.common._
import scalismo.geometry.{ Point, _3D }
import scalismo.image.DiscreteScalarImage
import scalismo.mesh.TriangleMesh
import scalismo.numerics.Sampler
import scalismo.registration.{ LandmarkRegistration, RigidTransformation, Transformation }
import scalismo.statisticalmodel.{ MultivariateNormalDistribution, StatisticalMeshModel }

import scala.collection.immutable
import scala.util.{ Failure, Try }

object ActiveShapeModel {
  type TrainingData = immutable.IndexedSeq[(DiscreteScalarImage[_3D, Float], Transformation[_3D])]
  // just a type alias to clarify intent
  type PointId = Int

  /**
   * Train an active shape model using an existing PCA model
   */
  def trainModel(statisticalModel: StatisticalMeshModel, trainingData: TrainingData, preprocessor: ImagePreprocessor, featureExtractor: FeatureExtractor, sampler: TriangleMesh => Sampler[_3D]): ActiveShapeModel = {

    val sampled = sampler(statisticalModel.referenceMesh).sample.map(_._1).to[immutable.IndexedSeq]
    val (points, pointIds) = sampled.map(statisticalModel.referenceMesh.findClosestPoint).unzip

    // preprocessed images can be expensive in terms of memory, so we go through them one at a time.
    val imageFeatures = trainingData.flatMap {
      case (image, transform) =>
        val (pimg, mesh) = (preprocessor(image), statisticalModel.referenceMesh.transform(transform))
        pointIds.map { pointId => featureExtractor(pimg, mesh, mesh.points(pointId)) }
    }

    // the structure is "wrongly nested" now, like: {img1:{pt1,pt2}, img2:{pt1,pt2}} (flattened).
    // We merge the corresponding points together, then estimate an MVD.
    val pointsLength = pointIds.length
    val imageRange = trainingData.indices.toIndexedSeq
    val pointFeatures = (0 until pointsLength).toIndexedSeq.map { pointIndex =>
      val featuresForPoint = imageRange.flatMap { imageIndex =>
        imageFeatures(imageIndex * pointsLength + pointIndex)
      }
      MultivariateNormalDistribution.estimateFromData(featuresForPoint)
    }
<commit_msg>ASM Training: use iterator instead of IndexedSeq<commit_after>/*
 * Copyright 2015 University of Basel, Graphics and Vision Research Group
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package scalismo.statisticalmodel.asm

import breeze.linalg.DenseVector
import scalismo.common._
import scalismo.geometry.{ Point, _3D }
import scalismo.image.DiscreteScalarImage
import scalismo.mesh.TriangleMesh
import scalismo.numerics.Sampler
import scalismo.registration.{ LandmarkRegistration, RigidTransformation, Transformation }
import scalismo.statisticalmodel.{ MultivariateNormalDistribution, StatisticalMeshModel }

import scala.collection.immutable
import scala.util.{ Failure, Try }

object ActiveShapeModel {
  type TrainingData = Iterator[(DiscreteScalarImage[_3D, Float], Transformation[_3D])]
  // just a type alias to clarify intent
  type PointId = Int

  /**
   * Train an active shape model using an existing PCA model
   */
  def trainModel(statisticalModel: StatisticalMeshModel, trainingData: TrainingData, preprocessor: ImagePreprocessor, featureExtractor: FeatureExtractor, sampler: TriangleMesh => Sampler[_3D]): ActiveShapeModel = {

    val sampled = sampler(statisticalModel.referenceMesh).sample.map(_._1).to[immutable.IndexedSeq]
    val (points, pointIds) = sampled.map(statisticalModel.referenceMesh.findClosestPoint).unzip

    // preprocessed images can be expensive in terms of memory, so we go through them one at a time.
    val imageFeatures = trainingData.flatMap {
      case (image, transform) =>
        val (pimg, mesh) = (preprocessor(image), statisticalModel.referenceMesh.transform(transform))
        pointIds.map { pointId => featureExtractor(pimg, mesh, mesh.points(pointId)) }
    }.toIndexedSeq

    // the structure is "wrongly nested" now, like: {img1:{pt1,pt2}, img2:{pt1,pt2}} (flattened).
    // We merge the corresponding points together, then estimate an MVD.
    val pointsLength = pointIds.length
    val imageRange = (0 until imageFeatures.length / pointsLength).toIndexedSeq
    val pointFeatures = (0 until pointsLength).toIndexedSeq.map { pointIndex =>
      val featuresForPoint = imageRange.flatMap { imageIndex =>
        imageFeatures(imageIndex * pointsLength + pointIndex)
      }
      MultivariateNormalDistribution.estimateFromData(featuresForPoint)
    }

{'fraction_non_alphanumeric': 0.08349687778768956, 'fraction_numerical': 0.007314897413024085, 'mean_word_length': 4.55049504950495, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4824297', 'n_tokens_mistral': 1554, 'n_tokens_neox': 1485, 'n_words': 492}