<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 org.apache.sysml.runtime.matrix.data;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.math3.random.Well1024a;
import org.apache.sysml.hops.DataGenOp;
import org.apache.sysml.runtime.DMLRuntimeException;
import org.apache.sysml.runtime.controlprogram.parfor.util.IDSequence;
import org.apache.sysml.runtime.util.NormalPRNGenerator;
import org.apache.sysml.runtime.util.PRNGenerator;
import org.apache.sysml.runtime.util.PoissonPRNGenerator;
import org.apache.sysml.runtime.util.UniformPRNGenerator;

/**
 *  
 */
public class LibMatrixDatagen 
{
	protected static final Log LOG = LogFactory.getLog(LibMatrixDatagen.class.getName());
	public static final String RAND_PDF_UNIFORM = "uniform";
	public static final String RAND_PDF_NORMAL = "normal";
	public static final String RAND_PDF_POISSON = "poisson";
	
	private static IDSequence _seqRandInput = new IDSequence(); 
	
	private LibMatrixDatagen() {
		//prevent instantiation via private constructor
	}
	
	/**
	 * 
	 * @param min
	 * @param max
	 * @param sparsity
	 * @param pdf
	 * @return
	 */
	public static boolean isShortcutRandOperation( double min, double max, double sparsity, String pdf )
	{
		return pdf.equalsIgnoreCase(RAND_PDF_UNIFORM)
			   && (  ( min == 0.0 && max == 0.0 ) //all zeros
				   ||( sparsity==1.0d && min == max )); //equal values
	}
	
	/**
	 * 
	 * @param seq_from
	 * @param seq_to
	 * @param seq_incr
	 * @return
	 */
	public static double updateSeqIncr(double seq_from, double seq_to, double seq_incr) {
		//handle default 1 to -1 for special case of from>to
		return (seq_from>seq_to && seq_incr==1)? -1 : seq_incr;
	}
	
	/**
	 * 
	 * @param basedir
	 * @return
	 */
	public static String generateUniqueSeedPath( String basedir ) {
		return basedir + "tmp" + _seqRandInput.getNextID() + ".randinput";
	}
	
	/**
	 * A matrix of random numbers is generated by using multiple seeds, one for each 
	 * block. Such block-level seeds are produced via Well equidistributed long-period linear 
	 * generator (Well1024a). For a given seed, this function sets up the block-level seeds.
	 * 
	 * This function is invoked from both CP (RandCPInstruction.processInstruction()) 
	 * as well as MR (RandMR.java while setting up the Rand job).
	 * 
	 * @param seed
	 * @return
	 */
	public static Well1024a setupSeedsForRand(long seed) 
	{
		long lSeed = (seed == DataGenOp.UNSPECIFIED_SEED ? DataGenOp.generateRandomSeed() : seed);
		LOG.trace("Setting up RandSeeds with initial seed = "+lSeed+".");

		Random random=new Random(lSeed);
		Well1024a bigrand=new Well1024a();
		//random.setSeed(lSeed);
		int[] seeds=new int[32];
		for(int s=0; s<seeds.length; s++)
			seeds[s]=random.nextInt();
		bigrand.setSeed(seeds);
		
		return bigrand;
	}
	
	/**
	 * 
	 * @param nrow
	 * @param ncol
	 * @param brlen
	 * @param bclen
	 * @param sparsity
	 * @return
	 * @throws DMLRuntimeException
	 */
	public static long[] computeNNZperBlock(long nrow, long ncol, int brlen, int bclen, double sparsity) throws DMLRuntimeException {
		int numBlocks = (int) (Math.ceil((double)nrow/brlen) * Math.ceil((double)ncol/bclen));
		
		// CURRENT: 
		// 		Total #of NNZ is set to the expected value (nrow*ncol*sparsity).
		// TODO: 
		//		Instead of using the expected value, one should actually 
		// 		treat NNZ as a random variable and accordingly generate a random value.
		long nnz = (long) Math.ceil (nrow * (ncol*sparsity));

		if ( numBlocks > Integer.MAX_VALUE ) {
			throw new DMLRuntimeException("A random matrix of size [" + nrow + "," + ncol + "] can not be created. Number of blocks (" +  numBlocks + ") exceeds the maximum integer size. Try to increase the block size.");
		}
		
		// Compute block-level NNZ
		long[] ret  = new long[numBlocks];
		
		if ( nnz < numBlocks ) {
			// Ultra-sparse matrix
			
			// generate the number of blocks with at least one non-zero
			// = a random number between [1,nnz]
			Random runif = new Random(System.nanoTime());
			int numNZBlocks = 1;
			if(nnz-1 > 0)
				numNZBlocks += runif.nextInt((int)(nnz-1)); // To avoid exception from random.nextInt(0) 
			
			// distribute non-zeros across numNZBlocks

			// compute proportions for each nzblock 
			// - divide (0,1] interval into numNZBlocks portions of random size
			double[] blockNNZproportions = new double[numNZBlocks];
			
			runif.setSeed(System.nanoTime());
			for(int i=0; i < numNZBlocks-1; i++) {
				blockNNZproportions[i] = runif.nextDouble();
			}<commit_msg>Fix error handling ultra-sparse data generation (int overflow)<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 org.apache.sysml.runtime.matrix.data;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.math3.random.Well1024a;
import org.apache.sysml.hops.DataGenOp;
import org.apache.sysml.runtime.DMLRuntimeException;
import org.apache.sysml.runtime.controlprogram.parfor.util.IDSequence;
import org.apache.sysml.runtime.util.NormalPRNGenerator;
import org.apache.sysml.runtime.util.PRNGenerator;
import org.apache.sysml.runtime.util.PoissonPRNGenerator;
import org.apache.sysml.runtime.util.UniformPRNGenerator;

/**
 *  
 */
public class LibMatrixDatagen 
{
	protected static final Log LOG = LogFactory.getLog(LibMatrixDatagen.class.getName());
	public static final String RAND_PDF_UNIFORM = "uniform";
	public static final String RAND_PDF_NORMAL = "normal";
	public static final String RAND_PDF_POISSON = "poisson";
	
	private static IDSequence _seqRandInput = new IDSequence(); 
	
	private LibMatrixDatagen() {
		//prevent instantiation via private constructor
	}
	
	/**
	 * 
	 * @param min
	 * @param max
	 * @param sparsity
	 * @param pdf
	 * @return
	 */
	public static boolean isShortcutRandOperation( double min, double max, double sparsity, String pdf )
	{
		return pdf.equalsIgnoreCase(RAND_PDF_UNIFORM)
			   && (  ( min == 0.0 && max == 0.0 ) //all zeros
				   ||( sparsity==1.0d && min == max )); //equal values
	}
	
	/**
	 * 
	 * @param seq_from
	 * @param seq_to
	 * @param seq_incr
	 * @return
	 */
	public static double updateSeqIncr(double seq_from, double seq_to, double seq_incr) {
		//handle default 1 to -1 for special case of from>to
		return (seq_from>seq_to && seq_incr==1)? -1 : seq_incr;
	}
	
	/**
	 * 
	 * @param basedir
	 * @return
	 */
	public static String generateUniqueSeedPath( String basedir ) {
		return basedir + "tmp" + _seqRandInput.getNextID() + ".randinput";
	}
	
	/**
	 * A matrix of random numbers is generated by using multiple seeds, one for each 
	 * block. Such block-level seeds are produced via Well equidistributed long-period linear 
	 * generator (Well1024a). For a given seed, this function sets up the block-level seeds.
	 * 
	 * This function is invoked from both CP (RandCPInstruction.processInstruction()) 
	 * as well as MR (RandMR.java while setting up the Rand job).
	 * 
	 * @param seed
	 * @return
	 */
	public static Well1024a setupSeedsForRand(long seed) 
	{
		long lSeed = (seed == DataGenOp.UNSPECIFIED_SEED ? DataGenOp.generateRandomSeed() : seed);
		LOG.trace("Setting up RandSeeds with initial seed = "+lSeed+".");

		Random random=new Random(lSeed);
		Well1024a bigrand=new Well1024a();
		//random.setSeed(lSeed);
		int[] seeds=new int[32];
		for(int s=0; s<seeds.length; s++)
			seeds[s]=random.nextInt();
		bigrand.setSeed(seeds);
		
		return bigrand;
	}
	
	/**
	 * 
	 * @param nrow
	 * @param ncol
	 * @param brlen
	 * @param bclen
	 * @param sparsity
	 * @return
	 * @throws DMLRuntimeException
	 */
	public static long[] computeNNZperBlock(long nrow, long ncol, int brlen, int bclen, double sparsity) 
		throws DMLRuntimeException 
	{
		long lnumBlocks = (long) (Math.ceil((double)nrow/brlen) * Math.ceil((double)ncol/bclen));
		
		//sanity check max number of blocks (before cast to avoid overflow)
		if ( lnumBlocks > Integer.MAX_VALUE ) {
			throw new DMLRuntimeException("A random matrix of size [" + nrow + "," + ncol + "] can not be created. "
					+ "Number of blocks ("+lnumBlocks+") exceeds the maximum integer size. Try to increase the block size.");
		}

		// NOTE: Total #of NNZ is set to the expected value (nrow*ncol*sparsity).
		// TODO: Instead of using the expected value, NNZ should be random variable 
		
		int numBlocks = (int) lnumBlocks;
		long nnz = (long) Math.ceil (nrow * (ncol*sparsity));
		
		// Compute block-level NNZ
		long[] ret  = new long[numBlocks];
		
		if ( nnz < numBlocks ) {
			// Ultra-sparse matrix
			
			// generate the number of blocks with at least one non-zero
			// = a random number between [1,nnz]
			Random runif = new Random(System.nanoTime());
			int numNZBlocks = 1;
			if(nnz-1 > 0)
				numNZBlocks += runif.nextInt((int)(nnz-1)); // To avoid exception from random.nextInt(0) 
			
			// distribute non-zeros across numNZBlocks

			// compute proportions for each nzblock 
			// - divide (0,1] interval into numNZBlocks portions of random size
			double[] blockNNZproportions = new double[numNZBlocks];
			
			runif.setSeed(System.nanoTime());
			for(int i=0; i < numNZBlocks-1; i++) {
				blockNNZproportions[i] = runif.nextDouble();
			}
{'fraction_non_alphanumeric': 0.10846940606495604, 'fraction_numerical': 0.008612955320294276, 'mean_word_length': 3.687552565180824, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 11, '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': '7152392', 'n_tokens_mistral': 3837, 'n_tokens_neox': 3427, 'n_words': 1088}