This function fits objects passed to Multivar, guarantees wave ordering in
        Catalog object and DesignMatrix object matches up
545342
def _run_arguement_object_fits(self):
        
        # run fits
        # fit catalog object
        Y_dict = self._catalog_object.get_transformed_Y()
        # fit designmatrix object
        X = self._designmatrix_object.get_matrix()
        Xcol_names = self._designmatrix_object.get_columnnames()
        row_names = self._designmatrix_object.get_rownames()
        # make sure waveforms are matched
        # loop through Xrow_names, use as key for Y_dict, populate Y_matrix
        Y = np.empty((len(row_names),len(Y_dict[Y_dict.keys()[0]])))

        # check if waveforms are complex valued.  if so, instantiate Y as complex type
        if sum(np.iscomplex(Y_dict[Y_dict.keys()[0]])):
            # then it is complex
            Y = np.empty((len(row_names),len(Y_dict[Y_dict.keys()[0]]))).astype(np.complex)

        for i in np.arange(0,len(row_names)):
            Y[i,:] = Y_dict[row_names[i]]
        # fit basis object
        A = self._basis_object.fit_transform(Y)
        return Y, X, A, Xcol_names, row_names
613224
function coordMatrixToCoordArray(coordMatrix) {
                var coodinatesArray = new Array(coordMatrix.length * coordMatrix[0].length);
                var k = 0;
                for (var i = 0; i < coordMatrix[0].length; ++i) {
                    for (var j = 0; j < coordMatrix.length; ++j) {
                        coodinatesArray[k] = coordMatrix[j][i];
                        ++k;
                    }
                }

                return coodinatesArray;
            }
4858
function getShapeTwo(x,y,options,modules,mod_matrix){

  var EOL = '\r\n';
  var width = options.width;
  var height = options.height;
  var length = modules.length;
  var style = options.style;
  var xsize = width / (length + 2 * options.padding);
  var ysize = height / (length + 2 * options.padding);
  var px = (x * xsize + options.padding * xsize);
  var py = (y * ysize + options.padding * ysize);

  //If in the middle of a straight line, return a 1b3b
  if( (mod_matrix.top && mod_matrix.bottom) || (mod_matrix.left && mod_matrix.right) ){
    var orientation = (mod_matrix.top && mod_matrix.bottom) ? 0 : 90;
    switch(options.style){
      case 'square':
        return '<rect transform="rotate('+orientation+' '+(px+xsize/2)+' '+(py+ysize/2)+')"  x="' + px + '" y="' + py + '" width="' + xsize + '" height="' + ysize + '" style="fill:' + options.color + ';shape-rendering:crispEdges;"/>' + EOL;
      case 'circle':
        return '<rect transform="rotate('+orientation+' '+(px+xsize/2)+' '+(py+ysize/2)+')" rx="'+xsize+'" x="' + px + '" y="' + py + '" width="' + xsize + '" height="' + ysize + '" style="fill:' + options.color + ';shape-rendering:crispEdges;"/>' + EOL;
      case 'sharp-edge':
        return '<rect transform="rotate('+orientation+' '+(px+xsize/2)+' '+(py+ysize/2)+')" x="' + px + '" y="' + py + '" width="' + xsize + '" height="' + ysize + '" style="fill:' + options.color + ';shape-rendering:crispEdges;"/>' + EOL;
    }
  }

  //If a diagonal is in between the two surrounding (module is on a corner), return a 2a1b1a
  if(mod_matrix.topLeft || mod_matrix.topRight || mod_matrix.bottomLeft || mod_matrix.bottomRight){

    var orientation = 0;
    if(mod_matrix.top && mod_matrix.topRight && mod_matrix.right){orientation=90;}
    else if(mod_matrix.right && mod_matrix.bottomRight && mod_matrix.bottom){orientation=180;}
    else if(mod_matrix.left && mod_matrix.bottomLeft && mod_matrix.bottom){orientation=270;}

    switch(options.style){
      case 'square':
        return '<rect transform="rotate('+orientation+' '+(px+xsize/2)+' '+(py+ysize/2)+')"  x="' + px + '" y="' + py + '" width="' + xsize + '" height="' + ysize + '" style="fill:' + options.color + ';shape-rendering:crispEdges;"/>' + EOL;
      case 'circle':
        return '<rect transform="rotate('+orientation+' '+(px+xsize/2)+' '+(py+ysize/2)+')" rx="'+xsize+'" x="' + px + '" y="' + py + '" width="' + xsize + '" height="' + ysize + '" style="fill:' + options.color + ';shape-rendering:crispEdges;"/>' + EOL;
      case 'sharp-edge':
        return '<rect transform="rotate('+orientation+' '+(px+xsize/2)+' '+(py+ysize/2)+')" x="' + px + '" y="' + py + '" width="' + xsize + '" height="' + ysize + '" style="fill:' + options.color + ';shape-rendering:crispEdges;"/>' + EOL;
    }
  }

  //Else in the center of a right angle
  var orientation = 0;
  if(mod_matrix.top && mod_matrix.right){orientation=90;}
  else if(mod_matrix.right && mod_matrix.bottom){orientation=180;}
  else if(mod_matrix.bottom && mod_matrix.left){orientation=270;}

  switch(options.style){
    case 'square':
      return '<rect transform="rotate('+orientation+' '+(px+xsize/2)+' '+(py+ysize/2)+')"  x="' + px + '" y="' + py + '" width="' + xsize + '" height="' + ysize + '" style="fill:' + options.color + ';shape-rendering:crispEdges;"/>' + EOL;
    case 'circle':
      return '<rect transform="rotate('+orientation+' '+(px+xsize/2)+' '+(py+ysize/2)+')"  rx="'+xsize+'" x="' + px + '" y="' + py + '" width="' + xsize + '" height="' + ysize + '" style="fill:' + options.color + ';shape-rendering:crispEdges;"/>' + EOL;
    case 'sharp-edge':
      return '<rect transform="rotate('+orientation+' '+(px+xsize/2)+' '+(py+ysize/2)+')" x="' + px + '" y="' + py + '" width="' + xsize + '" height="' + ysize + '" style="fill:' + options.color + ';shape-rendering:crispEdges;"/>' + EOL;
  }
}
1233496
def matrix_chain_mult(M):
    
    opt, arg = matrix_mult_opt_order(M)
    return _apply_order(M, arg, 0, len(M)-1)
29523
def returnMatches(kw, kv, n, theta, inputScaling=1.0):
  
  # How many weight vectors and input vectors to generate at a time
  m1 = 4
  m2 = 1000

  weights = getSparseTensor(kw, n, m1, fixedRange=1.0 / kw)

  # Initialize random input vectors using given scaling and see how many match
  inputVectors = getSparseTensor(kv, n, m2,
                                 onlyPositive=True,
                                 fixedRange= 2*inputScaling / kw,
                                 )
  dot = inputVectors.matmul(weights.t())
  numMatches = ((dot >= theta).sum()).item()
  pctMatches = numMatches / float(m1*m2)

  return pctMatches, numMatches, m1*m2
1120495
def distribute_covar_matrix_to_match_covariance_type(
        tied_cv, covariance_type, n_components):
    """"""
    if covariance_type == 'spherical':
        cv = np.tile(tied_cv.mean() * np.ones(tied_cv.shape[1]),
                     (n_components, 1))
    elif covariance_type == 'tied':
        cv = tied_cv
    elif covariance_type == 'diag':
        cv = np.tile(np.diag(tied_cv), (n_components, 1))
    elif covariance_type == 'full':
        cv = np.tile(tied_cv, (n_components, 1, 1))
    else:
        raise ValueError("covariance_type must be one of " +
                         "'spherical', 'tied', 'diag', 'full'")
    return cv
109256
def get_draws_stan3(fit, model=None, variables=None, ignore=None):
    """"""
    if ignore is None:
        ignore = []

    dtypes = {}
    if model is not None:
        dtypes = infer_dtypes(fit, model)

    if variables is None:
        variables = fit.param_names
    elif isinstance(variables, str):
        variables = [variables]
    variables = list(variables)

    data = OrderedDict()

    for var in variables:
        if var in data:
            continue
        dtype = dtypes.get(var)

        # in future fix the correct number of draws if fit.save_warmup is True
        new_shape = (*fit.dims[fit.param_names.index(var)], -1, fit.num_chains)
        values = fit._draws[fit._parameter_indexes(var), :]  # pylint: disable=protected-access
        values = values.reshape(new_shape, order="F")
        values = np.moveaxis(values, [-2, -1], [1, 0])
        values = values.astype(dtype)
        data[var] = values

    return data
206066
def manage_fits(list_of_frame):
    """"""

    import astropy.io.fits as fits
    import numina.types.dataframe as df

    refs = []
    for frame in list_of_frame:
        if isinstance(frame, str):
            ref = fits.open(frame)
            refs.append(ref)
        elif isinstance(frame, fits.HDUList):
            refs.append(frame)
        elif isinstance(frame, df.DataFrame):
            ref = frame.open()
            refs.append(ref)
        else:
            refs.append(frame)
    try:
        yield refs
    finally:
        # release
        for obj in refs:
            obj.close()
868671
function createUniformWrapper(gl, program, uniforms, locations) {

  function makeGetter(index) {
    var proc = new Function('gl', 'prog', 'locations', 
      'return function(){return gl.getUniform(prog,locations[' + index + '])}') 
    return proc(gl, program, locations)
  }

  function makePropSetter(path, index, type) {
    switch(type) {
      case 'bool':
      case 'int':
      case 'sampler2D':
      case 'samplerCube':
        return 'gl.uniform1i(locations[' + index + '],obj' + path + ')'
      case 'float':
        return 'gl.uniform1f(locations[' + index + '],obj' + path + ')'
      default:
        var vidx = type.indexOf('vec')
        if(0 <= vidx && vidx <= 1 && type.length === 4 + vidx) {
          var d = type.charCodeAt(type.length-1) - 48
          if(d < 2 || d > 4) {
            throw new Error('gl-shader: Invalid data type')
          }
          switch(type.charAt(0)) {
            case 'b':
            case 'i':
              return 'gl.uniform' + d + 'iv(locations[' + index + '],obj' + path + ')'
            case 'v':
              return 'gl.uniform' + d + 'fv(locations[' + index + '],obj' + path + ')'
            default:
              throw new Error('gl-shader: Unrecognized data type for vector ' + name + ': ' + type)
          }
        } else if(type.indexOf('mat') === 0 && type.length === 4) {
          var d = type.charCodeAt(type.length-1) - 48
          if(d < 2 || d > 4) {
            throw new Error('gl-shader: Invalid uniform dimension type for matrix ' + name + ': ' + type)
          }
          return 'gl.uniformMatrix' + d + 'fv(locations[' + index + '],false,obj' + path + ')'
        } else {
          throw new Error('gl-shader: Unknown uniform data type for ' + name + ': ' + type)
        }
      break
    }
  }

  function enumerateIndices(prefix, type) {
    if(typeof type !== 'object') {
      return [ [prefix, type] ]
    }
    var indices = []
    for(var id in type) {
      var prop = type[id]
      var tprefix = prefix
      if(parseInt(id) + '' === id) {
        tprefix += '[' + id + ']'
      } else {
        tprefix += '.' + id
      }
      if(typeof prop === 'object') {
        indices.push.apply(indices, enumerateIndices(tprefix, prop))
      } else {
        indices.push([tprefix, prop])
      }
    }
    return indices
  }

  function makeSetter(type) {
    var code = [ 'return function updateProperty(obj){' ]
    var indices = enumerateIndices('', type)
    for(var i=0; i<indices.length; ++i) {
      var item = indices[i]
      var path = item[0]
      var idx  = item[1]
      if(locations[idx]) {
        code.push(makePropSetter(path, idx, uniforms[idx].type))
      }
    }
    code.push('return obj}')
    var proc = new Function('gl', 'prog', 'locations', code.join('\n'))
    return proc(gl, program, locations)
  }

  function defaultValue(type) {
    switch(type) {
      case 'bool':
        return false
      case 'int':
      case 'sampler2D':
      case 'samplerCube':
        return 0
      case 'float':
        return 0.0
      default:
        var vidx = type.indexOf('vec')
        if(0 <= vidx && vidx <= 1 && type.length === 4 + vidx) {
          var d = type.charCodeAt(type.length-1) - 48
          if(d < 2 || d > 4) {
            throw new Error('gl-shader: Invalid data type')
          }
          if(type.charAt(0) === 'b') {
            return dup(d, false)
          }
          return dup(d)
        } else if(type.indexOf('mat') === 0 && type.length === 4) {
          var d = type.charCodeAt(type.length-1) - 48
          if(d < 2 || d > 4) {
            throw new Error('gl-shader: Invalid uniform dimension type for matrix ' + name + ': ' + type)
          }
          return dup([d,d])
        } else {
          throw new Error('gl-shader: Unknown uniform data type for ' + name + ': ' + type)
        }
      break
    }
  }

  function storeProperty(obj, prop, type) {
    if(typeof type === 'object') {
      var child = processObject(type)
      Object.defineProperty(obj, prop, {
        get: identity(child),
        set: makeSetter(type),
        enumerable: true,
        configurable: false
      })
    } else {
      if(locations[type]) {
        Object.defineProperty(obj, prop, {
          get: makeGetter(type),
          set: makeSetter(type),
          enumerable: true,
          configurable: false
        })
      } else {
        obj[prop] = defaultValue(uniforms[type].type)
      }
    }
  }

  function processObject(obj) {
    var result
    if(Array.isArray(obj)) {
      result = new Array(obj.length)
      for(var i=0; i<obj.length; ++i) {
        storeProperty(result, i, obj[i])
      }
    } else {
      result = {}
      for(var id in obj) {
        storeProperty(result, id, obj[id])
      }
    }
    return result
  }

  //Return data
  var coallesced = coallesceUniforms(uniforms, true)
  return {
    get: identity(processObject(coallesced)),
    set: makeSetter(coallesced),
    enumerable: true,
    configurable: true
  }
}
916001
def simxSetSphericalJointMatrix(clientID, jointHandle, matrix, operationMode):
    '''
    
    '''
    matrix = (ct.c_float*12)(*matrix)
    return c_SetSphericalJointMatrix(clientID, jointHandle, matrix, operationMode)
684863
def fit_apply(fit_result,vec_array):
    '''
    '''

    return map( lambda x,t1=fit_result[0],mt2=negate(fit_result[1]),
        m=fit_result[2]: add(t1,transform(m,add(mt2,x))),vec_array)
488268
def polyfit2d(x, y, z, order=3 #bounds=None
              ):
    '''
     
    '''
    ncols = (order + 1)**2
    G = np.zeros((x.size, ncols))
    ij = itertools.product(list(range(order+1)), list(range(order+1)))
    for k, (i,j) in enumerate(ij):
        G[:,k] = x**i * y**j
    m = np.linalg.lstsq(G, z)[0]
    return m
213
public static void checkSvdMatrixSize(DMatrixRMaj U, boolean tranU, DMatrixRMaj W, DMatrixRMaj V, boolean tranV ) {
        int numSingular = Math.min(W.numRows,W.numCols);
        boolean compact = W.numRows == W.numCols;

        if( compact ) {
            if( U != null ) {
                if( tranU && U.numRows != numSingular )
                    throw new IllegalArgumentException("Unexpected size of matrix U");
                else if( !tranU && U.numCols != numSingular )
                    throw new IllegalArgumentException("Unexpected size of matrix U");
            }

            if( V != null ) {
            if( tranV && V.numRows != numSingular )
                throw new IllegalArgumentException("Unexpected size of matrix V");
            else if( !tranV && V.numCols != numSingular )
                throw new IllegalArgumentException("Unexpected size of matrix V");
            }
        } else {
            if( U != null && U.numRows != U.numCols )
                throw new IllegalArgumentException("Unexpected size of matrix U");
            if( V != null && V.numRows != V.numCols )
                throw new IllegalArgumentException("Unexpected size of matrix V");
            if( U != null && U.numRows != W.numRows )
                throw new IllegalArgumentException("Unexpected size of W");
            if( V != null && V.numRows != W.numCols )
                throw new IllegalArgumentException("Unexpected size of W");
        }
    }
841345
function foo (jointName, keyframe, jointParents, keyframeJointMatrices) {
  var jointMatrix = keyframeJointMatrices[keyframe][jointName]
  var parentJointName = jointParents[jointName].parent
  if (parentJointName) {
    return [jointMatrix].concat(foo(parentJointName, keyframe, jointParents, keyframeJointMatrices))
  }
  return [jointMatrix]
}
743454
def getProjectionMatrix(self, eEye, fNearZ, fFarZ):
        """"""

        fn = self.function_table.getProjectionMatrix
        result = fn(eEye, fNearZ, fFarZ)
        return result
742673
def _itemize(objs):
    """"""
    if not isinstance(objs, collections.Sequence):
        raise TypeError("expected a sequence of Function")

    isseq = [isinstance(obj, collections.Sequence) for obj in objs]
    if not any(isseq):
        ftype = None
        for obj in objs:
            if ftype is None:
                if isinstance(obj, BinaryDecisionDiagram):
                    ftype = BinaryDecisionDiagram
                elif isinstance(obj, Expression):
                    ftype = Expression
                elif isinstance(obj, TruthTable):
                    ftype = TruthTable
                else:
                    raise TypeError("expected valid Function inputs")
            elif not isinstance(obj, ftype):
                raise ValueError("expected uniform Function types")
        return list(objs), ((0, len(objs)), ), ftype
    elif all(isseq):
        items = list()
        shape = None
        ftype = None
        for obj in objs:
            _items, _shape, _ftype = _itemize(obj)
            if shape is None:
                shape = _shape
            elif shape != _shape:
                raise ValueError("expected uniform farray dimensions")
            if ftype is None:
                ftype = _ftype
            elif ftype != _ftype:
                raise ValueError("expected uniform Function types")
            items += _items
        shape = ((0, len(objs)), ) + shape
        return items, shape, ftype
    else:
        raise ValueError("expected uniform farray dimensions")
671189
def fit(self, X, y=None):
        
        X = self._check_array(X)

        if self.categories is not None:
            # some basic validation
            columns = pd.Index(self.categories)
            categories = self.categories

        elif isinstance(X, pd.DataFrame):
            columns, categories = self._fit(X)
        else:
            columns, categories = self._fit_dask(X)

        self.columns_ = columns
        self.categories_ = categories
        return self